我将使用OP_RETURN (testnet)将数据嵌入到区块链中。
我在一个目录中有两个文件。第一个keys.js包含为比特币testnet交易生成地址和私钥的代码。
keys.js:
const bitcoin = require('bitcoinjs-lib');
const { testnet } = bitcoin.networks
const myKeyPair = bitcoin.ECPair.makeRandom({ network: testnet });
//extract the publickey
const publicKey = myKeyPair.publicKey;
//get the private key
const myWIF = myKeyPair.toWIF();
//get an address from the myKeyPair we generated above.
const { address } = bitcoin.payments.p2pkh({
pubkey: publicKey,
network: testnet
});
console.log("myAdress: " + address + " \nmyWIF: " + myWIF);第二个op_return.js包含允许我将随机文本嵌入到区块链中的方法。
这是op_return.js的结尾:
const importantMessage = 'RANDOM TEXT INTO BLOCKCHAIN'
buildOpReturnTransaction(myKeyPair, importantMessage)
.then(pushTransaction)
.then(response => console.log(response.data))该问题与op_return.js中的常量myKeyPair有关,因为在node.js命令提示符中键入node op_return后会出现错误:
buildOpReturnTransaction(myKeyPair, importantMessage)
^
ReferenceError: myKeyPair is not defined
at Object.<anonymous> (C:\Users\Paul\Desktop\mydir\op_return:71:26)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47发布于 2020-05-15 01:00:52
在一个JavaScript文件中声明的变量不能在另一个文件中自动访问,但Node.js中有一项功能允许您通过modules导入和导出变量。
假设你在'file1.js‘中定义了变量myKeyPair,但是你想在'file2.js’中使用myKeyPair。
解决方案是在file1.js中导出myKeyPair:
// file1.js
const myKeyPair = ['hello', 'world'];
module.exports.myKeyPair = myKeyPair;然后,要在file2.js中使用myKeyPair,需要使用require()语句从file1.js导入它。
// file2.js
const myKeyPair = require('./file1.js');发布于 2020-05-15 00:33:02
您已经在keys.js中定义了myKeyPair,而不是在op_return.js中。如果需要在一个文件中定义该变量并在另一个文件中使用它,则需要将该变量定义为全局变量。有关节点中的全局变量,请查看以下链接
https://stackabuse.com/using-global-variables-in-node-js/
https://stackoverflow.com/questions/61802416
复制相似问题