从私钥生成比特币公共地址的尝试失败

时间:2019-04-02 08:07:21

标签: javascript blockchain

我有一个程序,可以从随机生成的私钥生成比特币公共地址。但是,当我在blockchain.info上测试公共地址的有效性时,它告诉我该地址无效。我在代码中哪里出错了?

//modules
const secureRandom = require("secure-random");
const elliptic = require("elliptic");
const ecdsa = new elliptic.ec('secp256k1');
const sha256 = require('js-sha256');
const ripemd160 = require('ripemd160');
const base58 = require('bs58');
//variable that caps the address possiblities due to elliptic curve limitations
const max = Buffer.from("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140","hex");
//generates a key that does not exceed 'max'
  function createWalletAddress(){
      var foundPrivateKey = false;
      var privateKey;
      while(!foundPrivateKey){
        privateKey=secureRandom.randomBuffer(32);
        if(Buffer.compare(max,privateKey)){
          foundPrivateKey=true
        }
      }
      //prints the private key generated
      console.log("Private: " +privateKey.toString("hex"))
      //turns private key into public and prints it
      var keys = ecdsa.keyFromPrivate(privateKey);
      var publicKey = keys.getPublic("hex");
      console.log("Public: "+publicKey);
      //getting the public key hash
      const hashBeforePKH = sha256(Buffer.from(publicKey, "hex"));
      const publicKeyHash = new ripemd160().update(Buffer.from(hashBeforePKH,"hex")).digest();
      console.log("PKH "+publicKeyHash.toString("hex"));
      return publicKeyHash;
  }

  function createPublicAddress(publicKeyHash){
      const addPrefix="00"+publicKeyHash.toString('hex');
      const hashAddress=sha256(addPrefix);
      const hashAgain = sha256(Buffer.from(hashAddress,"hex"));
      const checkSum = hashAgain.substring(0,8);
      const combine = addPrefix.toString("hex")+checkSum;
      const address= base58.encode(Buffer.from(combine,"hex"));
       console.log("address " + address);
  }

1 个答案:

答案 0 :(得分:0)

校验和计算错误,应为0xf38580e3

尝试对缓冲区而不是字符串进行哈希处理:

function createPublicAddress(publicKeyHash){
  const addPrefix="00"+publicKeyHash.toString('hex');
  const hashAddress=sha256(Buffer.from(addPrefix, 'hex'));
  ...
}

您也可以使用类似bs58check的方法来代替手动计算校验和。