4

我正在尝试使用 nodejs 验证来自 QLDB 的文档。我一直在尽可能多地关注Java 验证示例,但我无法计算出与分类帐中存储的摘要相同的摘要。

这是我想出的代码。我从 QLDB 查询证明和块哈希,然后尝试以与 Java 示例相同的方式计算摘要。但是在连接两个哈希并根据结果计算新哈希后,我得到了错误的输出crypto.createHash('sha256').update(c).digest("base64")。我也尝试过使用“base64”而不是“hex”,但结果不同。

  const rBlock = makeReader(res.Revision.IonText);

  var block = [];

  rBlock.next();
  rBlock.stepIn();
  rBlock.next();
  while (rBlock.next() != null) {
    if (rBlock.fieldName() == 'hash') {
      block.push(Buffer.from(rBlock.byteValue()).toString('hex'));
    }
  }

  console.log(block);

  var proof = [];

  const rProof = makeReader(res.Proof.IonText);
  rProof.next();

  rProof.stepIn();
  while (rProof.next() != null) {
    proof.push(Buffer.from(rProof.byteValue()).toString('hex'));
  }

  var ph = block[0];
  var c;
  for (var i = 0; i < proof.length; i++) {
    console.log(proof[i])

    for (var j = 0; j < ph.length; j++) {
      if (parseInt(ph[j]) > parseInt(proof[i][j])){
        c = ph + proof[i];
        break;
      }
      if (parseInt(ph[j]) < parseInt(proof[i][j])){
        c = proof[i] + ph;
        break;
      }
    }

    ph = crypto.createHash('sha256').update(c).digest("hex");
    console.log(ph);
    console.log();
  }
4

1 回答 1

2

我已经弄清楚了。问题是我正在将 blob 转换为十六进制字符串并散列它们而不是原始值。对于任何想要在节点中验证数据的人,这里是简单的解决方案:

ledgerInfo.getRevision(params).then(res => {
  console.log(res);

  const rBlock = makeReader(res.Revision.IonText);

  var ph;

  rBlock.next();
  rBlock.stepIn();
  rBlock.next();
  while (rBlock.next() != null) {
    if (rBlock.fieldName() == 'hash') {
      ph = rBlock.byteValue()
    }
  }

  var proof = [];

  const rProof = makeReader(res.Proof.IonText);
  rProof.next();

  rProof.stepIn();
  while (rProof.next() != null) {
    proof.push(rProof.byteValue());
  }

  for (var i = 0; i < proof.length; i++) {
    var c;

    if (hashComparator(ph, proof[i]) < 0) {
      c = concatTypedArrays(ph, proof[i]);
    }
    else {
      c = concatTypedArrays(proof[i], ph);
    }

    var buff = crypto.createHash('sha256').update(c).digest("hex");
    ph = Uint8Array.from(Buffer.from(buff, 'hex'));
  }

  console.log(Buffer.from(ph).toString('base64'));

}).catch(err => {
  console.log(err, err.stack)
});

function concatTypedArrays(a, b) {
  var c = new (a.constructor)(a.length + b.length);
  c.set(a, 0);
  c.set(b, a.length);
  return c;
}

function hashComparator(h1, h2) {
  for (var i = h1.length - 1; i >= 0; i--) {
    var diff = (h1[i]<<24>>24) - (h2[i]<<24>>24);
    if (diff != 0)
      return diff;
  }
  return 0;
}
于 2019-09-20T11:35:27.990 回答