AI 代码审查:用 JavaScript 验证 Merkle 一致性证明,别漏掉两份树大小

10-20 4阅读
AI 代码审查:用 JavaScript 验证 Merkle 一致性证明,别漏掉两份树大小
AI概念图。画面仅表达旧快照与新快照的关系,不是可据此实现的树形结构图。

审核 AI 生成的 Merkle 代码时,最容易被一个漂亮的布尔值说服:给定根哈希与若干路径节点,程序返回 true,似乎日志就已经可信了。对追加式日志来说,真正需要问的是:已经保存的旧快照,与现在收到的新快照,是否承诺了相同的历史前缀?这要求同时重建旧根和新根,也要求两边的树大小来自已认证的快照。只验证一个根,或者让证明响应替换本地保存的大小,都会把问题悄悄换掉。

本文只讨论一致性证明(consistency proof)。它检查两个指定快照之间的前缀关系,不检查某一条记录是否被收录,也不把包含证明再包装一遍。示例使用普通 UTF-8 字符串作为教学叶数据;真实证书透明度日志的叶编码、签名验证、日志身份和网络协议,需要由上层实现分别处理。本文的函数不执行这些工作,也不宣称返回 true 就完成了一次完整的安全审计。

历史范围也要先说清楚:RFC 6962 是 2013 年发布的实验性证书透明度规范,现已由 RFC 9162 取代。这里选择前者的 SHA-256 树与一致性证明定义,是为了审查这一特定格式的实现;后者补充的迭代验证算法可作为独立交叉检查依据,不能因此假定两代 CT 协议的线格式完全相同。参见 RFC 6962 的状态与第 2.1.2 节、RFC 9162 的第 1.3 节及第 2.1.4.2 节。

先写清楚函数到底接收什么

一个快照至少需要绑定日志身份、树大小和根哈希;在具体系统中,还会有版本、时间戳及认证材料。本例的纯计算函数只接受 oldSize、newSize、oldHex、newHex 和 proofHex。调用方必须先确认两份快照来自同一个预期日志、使用同一种树规则,并完成对应的认证流程。旧快照要从此前可信的本地状态读取,新快照要经上层核验后传入。证明服务提供的根与大小不能越过这条边界。

大小统一要求 BigInt,并限制在零至 2 的 64 次方减一之间。根与每个证明节点必须是恰好六十四个十六进制字符,即三十二字节。大小写都接受,但空格、前缀、奇数长度和非十六进制字符都拒绝。证明必须是普通数组形状,包含缺项的稀疏数组也会失败。函数针对来自普通数据解码的值设计,不把恶意 Proxy、访问器或任意对象执行环境纳入输入隔离承诺。

下面九段代码都能独立保存并运行,不需要 npm 依赖,也不需要先运行上一段。为了让复制行为可重复,后面的验证实验会重复放入完整验证器;实际项目应只维护一份实现。本文所列输出是在 Node.js v24.19.0 上执行获得,输出中没有随机值或外部日志查询结果。

示例 1:空树哈希与空叶哈希不是一回事

空日志是一个合法边界,但它不能被随便塞进一个全零摘要。空树对空字节串做 SHA-256;叶节点要在数据前添加一个零字节,内部节点则使用一个值为一的字节作为前缀。这里强调的是字节,字符零、字符串 00 和十六进制字面量表示出的单个零字节并不相同。

第一段不构建整棵树,只让审查者亲手确认三个基础断言。它也防止后续零大小分支把任意三十二字节值都当作合法空根。

保存为 01-domains.cjs,执行 node 01-domains.cjs。

'use strict';
const { createHash } = require('node:crypto');
const H = bytes => createHash('sha256').update(bytes).digest('hex');
const emptyTree = H(Buffer.alloc(0));
const emptyLeaf = H(Buffer.from([0]));
console.log('empty-tree=' + emptyTree);
console.log('empty-tree-equals-empty-leaf=' + (emptyTree === emptyLeaf));
const bytes = Buffer.from('log-entry', 'utf8');
console.log('prefix-matters=' +
  (H(Buffer.concat([Buffer.from([0]), bytes])) !== H(bytes)));

精确输出:

empty-tree=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
empty-tree-equals-empty-leaf=false
prefix-matters=true

本例使用 Buffer 明确承载字节,避免把十六进制文本本身当成待连接的摘要。SHA-256 的调用方式可查阅 Node.js createHash 文档。这些基础约定只是数据解释规则,不给叶内容赋予真实性。

示例 2:在入口处保住整数,而不是事后补救

很多 AI 生成实现会对树大小直接使用 Number 的右移运算。小测试看起来正确,较大的大小却可能在运算前就被压到三十二位。另一条更隐蔽的路径是先用 Number 读取十进制大整数,再转换成 BigInt;后一种转换不会找回已经丢失的低位。下面两个输出差异都来自实际执行,而不是推测。

parseSize 是本文自定义的十进制字符串适配器,只接受规范的无符号表示,并在转换前限制长度。它不是 RFC JSON 接口的完整解析器。若远端协议把大小放在 JSON 数字字段里,必须在数字被普通 JSON.parse 转为 Number 之前使用能保留大整数精度的解析策略;把解析后的不安全 Number 再转 BigInt 没有补救作用。

保存为 02-integers.cjs,执行 node 02-integers.cjs。

'use strict';
const decimal = '9007199254740993';
console.log('number=' + Number(decimal));
console.log('bigint=' + BigInt(decimal).toString());
console.log('number-shift=' + (4294967296 >> 1));
console.log('bigint-shift=' + (4294967296n >> 1n).toString());
const MAX = (1n << 64n) - 1n;
function parseSize(text) {
  if (typeof text !== 'string' || !/^(0|[1-9][0-9]{0,19})$/.test(text))
    throw new TypeError('size syntax');
  const size = BigInt(text);
  if (size > MAX) throw new RangeError('size range');
  return size;
}
console.log('max=' + parseSize('18446744073709551615').toString());
for (const bad of ['01', '-1', '18446744073709551616']) {
  try { parseSize(bad); } catch (e) { console.log(e.message); }
}

精确输出:

number=9007199254740992
bigint=9007199254740993
number-shift=0
bigint-shift=2147483648
max=18446744073709551615
size syntax
size syntax
size range

验证器本身刻意不接受字符串和 Number,以免隐式转换把调用错误藏起来。实际接入时,把线格式解析与算法分开测试:前者负责无损获得整数,后者只处理已经过检查的 BigInt。这个分层也方便在评审中定位到底是谁改变了树大小。

示例 3:独立生成小树的参考证明

要测试验证器,不能只让同一段代码先生成证明再自己接受。这里先给一个小规模参考生成器,直接按有序叶列表递归分割树,再生成一致性路径。它使用数组切片,适合有限教学数据,不用于把庞大日志全部加载进内存。生成器中的 Number 只是这些短数组的索引,并不承担外部 uint64 大小的解析。

七条记录下,从三个叶扩展到七个叶需要四个节点,而从四个叶扩展到七个叶只需要一个节点。原因是旧的四叶快照已经恰好是新树的一个完整左子树;旧的三叶快照则跨越了需要重新拼合的边界。证明长度不是一个固定常数,也不能直接拿包含路径的长度来套用。

保存为 03-reference-proof.cjs,执行 node 03-reference-proof.cjs。

'use strict';
const { createHash } = require('node:crypto');
const H = (...parts) => createHash('sha256').update(Buffer.concat(parts)).digest();
const leaf = s => H(Buffer.from([0]), Buffer.from(s, 'utf8'));
const branch = (a,b) => H(Buffer.from([1]), a, b);
function power(n) { let k=1; while(k*2<n) k*=2; return k; }
function root(items) {
  if (!items.length) return H(Buffer.alloc(0));
  if (items.length===1) return leaf(items[0]);
  const k=power(items.length);
  return branch(root(items.slice(0,k)),root(items.slice(k)));
}
function makeProof(m,items,known=true) {
  if(m===0 || m===items.length && known) return [];
  if(m===items.length) return [root(items)];
  const k=power(items.length);
  return m<=k
    ? [...makeProof(m,items.slice(0,k),known),root(items.slice(k))]
    : [...makeProof(m-k,items.slice(k),false),root(items.slice(0,k))];
}

const items = ['a','b','c','d','e','f','g'];
for (const m of [1,3,4,6,7]) {
  console.log(m + '->7 nodes=' + makeProof(m, items).length);
}
console.log('root3=' + root(items.slice(0,3)).toString('hex'));
console.log('root7=' + root(items).toString('hex'));

精确输出:

1->7 nodes=3
3->7 nodes=4
4->7 nodes=1
6->7 nodes=3
7->7 nodes=0
root3=36642e73c2540ab121e3a6bf9545b0a24982cd830eb13d3cd19de3ce6c021ec1
root7=4ae191939f548d9934740b88dea2c5cb89bb8870fc4505cd79dec6bbfaaee9cb

这个生成器只为受控且有效的 m 与数组构造测试样本;它不是对任意外部输入开放的服务端接口。全文真正的外部输入检查位于下一段验证器。参考生成器与验证器还会与另一种迭代算法交叉核对,以降低同源实现错误互相掩盖的机会。

示例 4:完整验证器,同时重建两份承诺

下面是完整实现。rebuild 返回一对值,分别是当前递归范围对应的旧承诺与新承诺。左分支中,右子树只进入新承诺;右分支中,左子树同时进入两份承诺。known 表示此时遇到的基础情况能否直接使用调用方给定的旧根,它不是一项由证明提供者自由声明的字段。

到达必须读取证明节点的位置时,take 会推进游标;读不到节点立即拒绝。退出递归后,还必须确认没有剩余节点,并分别比较旧根、新根。这个组合检查避免把验证写成只计算新根的一次折叠。哈希输入一直保持 Buffer,返回值才与已经严格解码的目标根比较。

代码限制证明最多六十五个节点,与 uint64 大小范围下所需的上界相容。split 只在大于一的递归规模上运行;规模严格缩小,递归层数受六十四位大小限制。这里没有对 Number 做位运算,也不会随着叶总数线性遍历真实记录。

保存为 04-full-verifier.cjs,执行 node 04-full-verifier.cjs。

'use strict';
const { createHash } = require('node:crypto');
const MAX_SIZE = (1n << 64n) - 1n;
const isSize = x => typeof x === 'bigint' && x >= 0n && x <= MAX_SIZE;
const isHash = x => typeof x === 'string' && /^[0-9a-fA-F]{64}$/.test(x);
const hash = (...parts) => createHash('sha256')
  .update(Buffer.concat(parts)).digest();
const EMPTY = hash(Buffer.alloc(0));
const node = (left, right) => hash(Buffer.from([1]), left, right);
function split(n) {
  let k = 1n;
  while (k * 2n < n) k *= 2n;
  return k;
}
function verifyConsistency(oldSize, newSize, oldHex, newHex, proofHex) {
  if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize) return false;
  if (!isHash(oldHex) || !isHash(newHex) || !Array.isArray(proofHex)) return false;
  if (proofHex.length > 65) return false;
  for (const h of proofHex) if (!isHash(h)) return false;
  const oldRoot = Buffer.from(oldHex, 'hex');
  const newRoot = Buffer.from(newHex, 'hex');
  const proof = proofHex.map(h => Buffer.from(h, 'hex'));
  if (oldSize === 0n) {
    return proof.length === 0 && oldRoot.equals(EMPTY)
      && (newSize !== 0n || newRoot.equals(EMPTY));
  }
  if (oldSize === newSize) {
    return proof.length === 0 && oldRoot.equals(newRoot);
  }
  let pos = 0;
  function take() {
    if (pos >= proof.length) throw new Error('short proof');
    return proof[pos++];
  }
  function rebuild(m, n, known) {
    if (m === n) {
      const root = known ? oldRoot : take();
      return [root, root];
    }
    const k = split(n);
    if (m <= k) {
      const [oldLeft, newLeft] = rebuild(m, k, known);
      const right = take();
      return [oldLeft, node(newLeft, right)];
    }
    const [oldRight, newRight] = rebuild(m - k, n - k, false);
    const left = take();
    return [node(left, oldRight), node(left, newRight)];
  }
  try {
    const [a, b] = rebuild(oldSize, newSize, true);
    return pos === proof.length && a.equals(oldRoot) && b.equals(newRoot);
  } catch (error) {
    if (error.message === 'short proof') return false;
    throw error;
  }
}
const oldHex = "36642e73c2540ab121e3a6bf9545b0a24982cd830eb13d3cd19de3ce6c021ec1";
const newHex = "4ae191939f548d9934740b88dea2c5cb89bb8870fc4505cd79dec6bbfaaee9cb";
const proofHex = [
  "597fcb31282d34654c200d3418fca5705c648ebf326ec73d8ddef11841f876d8",
  "d070dc5b8da9aea7dc0f5ad4c29d89965200059c9a0ceca3abd5da2492dcb71d",
  "b137985ff484fb600db93107c77b0365c80d78f5b429ded0fd97361d077999eb",
  "e286d3390665a7cdc759453bed0b00cded1842d757e3e6cfe87df53db177e725"
];

console.log('append=' + verifyConsistency(3n, 7n, oldHex, newHex, proofHex));
const changedRoot = "622a8146a4684990515b2a16220ec5bf91cb5ab59c0ee27ace49687568f80779";
const changedProof = [
  "597fcb31282d34654c200d3418fca5705c648ebf326ec73d8ddef11841f876d8",
  "d070dc5b8da9aea7dc0f5ad4c29d89965200059c9a0ceca3abd5da2492dcb71d",
  "3323bfbab165889c47325076deebbc4486ea137aa8d51878f03f17b63c8fd283",
  "e286d3390665a7cdc759453bed0b00cded1842d757e3e6cfe87df53db177e725"
];
console.log('rewrite-prefix=' +
  verifyConsistency(3n, 7n, oldHex, changedRoot, changedProof));

精确输出:

append=true
rewrite-prefix=false

第二个用例把历史中的 b 改成 B,再为这份改写后的七叶列表构造新根与证明。虽然改写后的数据自己能组成一棵树,但它无法通过原先三叶旧根的比较,于是返回 false。这个例子检查的是两个给定承诺之间的关系;它没有证明原始字符串就是现实世界中真实发生的事件。

本实现用递归方式对应 RFC 6962 的证明定义,没有把 RFC 9162 的逐步算法逐字改写成 JavaScript。catch 只把证明过短转换为 false,其他内部异常继续抛出,避免将程序故障静默伪装成普通验证失败。生产系统可进一步使用专门的错误类型和结构化结果,但不能删去任何结构或根的检查。

示例 5:最重要的反例:大小变化不一定让验证失败

不要在评审清单中写下一个错误断言:只要有人修改树大小,根比较一定失败。证明节点是子树摘要,本身并不携带一个可由验证器独立解出的叶数量。下面使用四叶旧根、七叶新根以及一个右子树摘要,却分别声称新大小是五、七和八;这三种大小都落在同一个顶层分割形状中,因此会得到相同的哈希组合。

这个实验是刻意的错误元数据用例。结果为 true 不代表这些声称的大小都对应实际生成数据,也不代表发现了 SHA-256 碰撞。它说明函数只能按传入的大小解释证明,不能从一个不透明摘要反推真实基数。树大小必须和根一起经过认证,不能指望一致性验证顺便替代快照认证。

保存为 05-trusted-sizes.cjs,执行 node 05-trusted-sizes.cjs。

'use strict';
const { createHash } = require('node:crypto');
const MAX_SIZE = (1n << 64n) - 1n;
const isSize = x => typeof x === 'bigint' && x >= 0n && x <= MAX_SIZE;
const isHash = x => typeof x === 'string' && /^[0-9a-fA-F]{64}$/.test(x);
const hash = (...parts) => createHash('sha256')
  .update(Buffer.concat(parts)).digest();
const EMPTY = hash(Buffer.alloc(0));
const node = (left, right) => hash(Buffer.from([1]), left, right);
function split(n) {
  let k = 1n;
  while (k * 2n < n) k *= 2n;
  return k;
}
function verifyConsistency(oldSize, newSize, oldHex, newHex, proofHex) {
  if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize) return false;
  if (!isHash(oldHex) || !isHash(newHex) || !Array.isArray(proofHex)) return false;
  if (proofHex.length > 65) return false;
  for (const h of proofHex) if (!isHash(h)) return false;
  const oldRoot = Buffer.from(oldHex, 'hex');
  const newRoot = Buffer.from(newHex, 'hex');
  const proof = proofHex.map(h => Buffer.from(h, 'hex'));
  if (oldSize === 0n) {
    return proof.length === 0 && oldRoot.equals(EMPTY)
      && (newSize !== 0n || newRoot.equals(EMPTY));
  }
  if (oldSize === newSize) {
    return proof.length === 0 && oldRoot.equals(newRoot);
  }
  let pos = 0;
  function take() {
    if (pos >= proof.length) throw new Error('short proof');
    return proof[pos++];
  }
  function rebuild(m, n, known) {
    if (m === n) {
      const root = known ? oldRoot : take();
      return [root, root];
    }
    const k = split(n);
    if (m <= k) {
      const [oldLeft, newLeft] = rebuild(m, k, known);
      const right = take();
      return [oldLeft, node(newLeft, right)];
    }
    const [oldRight, newRight] = rebuild(m - k, n - k, false);
    const left = take();
    return [node(left, oldRight), node(left, newRight)];
  }
  try {
    const [a, b] = rebuild(oldSize, newSize, true);
    return pos === proof.length && a.equals(oldRoot) && b.equals(newRoot);
  } catch (error) {
    if (error.message === 'short proof') return false;
    throw error;
  }
}
const oldHex = "33376a3bd63e9993708a84ddfe6c28ae58b83505dd1fed711bd924ec5a6239f0";
const newHex = "4ae191939f548d9934740b88dea2c5cb89bb8870fc4505cd79dec6bbfaaee9cb";
const proofHex = ["e286d3390665a7cdc759453bed0b00cded1842d757e3e6cfe87df53db177e725"];

console.log('claimed-4-to-7=' + verifyConsistency(4n,7n,oldHex,newHex,proofHex));
console.log('claimed-4-to-5=' + verifyConsistency(4n,5n,oldHex,newHex,proofHex));
console.log('claimed-4-to-8=' + verifyConsistency(4n,8n,oldHex,newHex,proofHex));

精确输出:

claimed-4-to-7=true
claimed-4-to-5=true
claimed-4-to-8=true

因此接口的安全边界不是只传入一个可信根。调用方需要把已认证的旧大小与旧根作为一组保存,把已认证的新大小与新根作为另一组核验,然后才请求这两个大小之间的证明。测试应该包含一些修改大小会失败的用例,也必须保留这个修改大小仍通过的反例,防止团队对返回值产生过度解释。

示例 6:拒绝短证明、尾随节点和顺序改写

证明是有序结构,不是可以排序或去重的哈希集合。审查时要特别看 AI 是否调用了 sort、是否允许补零、是否忽略不认识的尾随节点。任何这种看似友好的归一化,都可能让服务端错误或协议不匹配被掩盖。这里固定使用三到七的合法证明,只改变它的结构,因而能直接观察每项约束。

保存为 06-proof-shape.cjs,执行 node 06-proof-shape.cjs。

'use strict';
const { createHash } = require('node:crypto');
const MAX_SIZE = (1n << 64n) - 1n;
const isSize = x => typeof x === 'bigint' && x >= 0n && x <= MAX_SIZE;
const isHash = x => typeof x === 'string' && /^[0-9a-fA-F]{64}$/.test(x);
const hash = (...parts) => createHash('sha256')
  .update(Buffer.concat(parts)).digest();
const EMPTY = hash(Buffer.alloc(0));
const node = (left, right) => hash(Buffer.from([1]), left, right);
function split(n) {
  let k = 1n;
  while (k * 2n < n) k *= 2n;
  return k;
}
function verifyConsistency(oldSize, newSize, oldHex, newHex, proofHex) {
  if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize) return false;
  if (!isHash(oldHex) || !isHash(newHex) || !Array.isArray(proofHex)) return false;
  if (proofHex.length > 65) return false;
  for (const h of proofHex) if (!isHash(h)) return false;
  const oldRoot = Buffer.from(oldHex, 'hex');
  const newRoot = Buffer.from(newHex, 'hex');
  const proof = proofHex.map(h => Buffer.from(h, 'hex'));
  if (oldSize === 0n) {
    return proof.length === 0 && oldRoot.equals(EMPTY)
      && (newSize !== 0n || newRoot.equals(EMPTY));
  }
  if (oldSize === newSize) {
    return proof.length === 0 && oldRoot.equals(newRoot);
  }
  let pos = 0;
  function take() {
    if (pos >= proof.length) throw new Error('short proof');
    return proof[pos++];
  }
  function rebuild(m, n, known) {
    if (m === n) {
      const root = known ? oldRoot : take();
      return [root, root];
    }
    const k = split(n);
    if (m <= k) {
      const [oldLeft, newLeft] = rebuild(m, k, known);
      const right = take();
      return [oldLeft, node(newLeft, right)];
    }
    const [oldRight, newRight] = rebuild(m - k, n - k, false);
    const left = take();
    return [node(left, oldRight), node(left, newRight)];
  }
  try {
    const [a, b] = rebuild(oldSize, newSize, true);
    return pos === proof.length && a.equals(oldRoot) && b.equals(newRoot);
  } catch (error) {
    if (error.message === 'short proof') return false;
    throw error;
  }
}
const oldHex = "36642e73c2540ab121e3a6bf9545b0a24982cd830eb13d3cd19de3ce6c021ec1";
const newHex = "4ae191939f548d9934740b88dea2c5cb89bb8870fc4505cd79dec6bbfaaee9cb";
const proofHex = [
  "597fcb31282d34654c200d3418fca5705c648ebf326ec73d8ddef11841f876d8",
  "d070dc5b8da9aea7dc0f5ad4c29d89965200059c9a0ceca3abd5da2492dcb71d",
  "b137985ff484fb600db93107c77b0365c80d78f5b429ded0fd97361d077999eb",
  "e286d3390665a7cdc759453bed0b00cded1842d757e3e6cfe87df53db177e725"
];

const check = p => verifyConsistency(3n,7n,oldHex,newHex,p);
const swapped = [...proofHex];
[swapped[0], swapped[1]] = [swapped[1], swapped[0]];
const changed = [...proofHex];
changed[0] = (changed[0][0] === '0' ? '1' : '0') + changed[0].slice(1);
console.log('complete=' + check(proofHex));
console.log('truncated=' + check(proofHex.slice(0,-1)));
console.log('extra=' + check([...proofHex,proofHex[0]]));
console.log('swapped=' + check(swapped));
console.log('changed=' + check(changed));

精确输出:

complete=true
truncated=false
extra=false
swapped=false
changed=false

只比较最终新根还不够,必须确认所有需要的节点都读到了,而且输入没有多出来的节点。这个实现用游标精确消耗证明,因此多一个值和少一个值都有清楚的拒绝路径。测试中的换序与单字符改写也是针对当前固定样本的回归检查,不应把有限实验描述成对所有恶意输入的数学证明。

示例 7:零大小、相等大小与回退策略

RFC 的核心一致性构造针对旧大小严格大于零且小于新大小的情况。实际调用函数往往还会遇到启动时没有任何记录、重复收到同一快照、服务端返回更小快照等边界。本文显式增加包装策略:大小相等时,只接受相同根与空证明;旧大小为零时,只接受标准空根与空证明;新大小也为零时,再要求新根同样是标准空根;大小回退一律拒绝。

零到正数的 true 具有非常有限的含义:空列表没有历史前缀需要维护。这个分支不会利用空证明验证新树内部的叶,也不会证明新根真的来自一个指定大小的实际日志。调用方仍须先认证新快照。若应用策略要求首次使用必须取得额外证据,应在此函数之外实施,而不要误读这个布尔值。

保存为 07-boundaries.cjs,执行 node 07-boundaries.cjs。

'use strict';
const { createHash } = require('node:crypto');
const MAX_SIZE = (1n << 64n) - 1n;
const isSize = x => typeof x === 'bigint' && x >= 0n && x <= MAX_SIZE;
const isHash = x => typeof x === 'string' && /^[0-9a-fA-F]{64}$/.test(x);
const hash = (...parts) => createHash('sha256')
  .update(Buffer.concat(parts)).digest();
const EMPTY = hash(Buffer.alloc(0));
const node = (left, right) => hash(Buffer.from([1]), left, right);
function split(n) {
  let k = 1n;
  while (k * 2n < n) k *= 2n;
  return k;
}
function verifyConsistency(oldSize, newSize, oldHex, newHex, proofHex) {
  if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize) return false;
  if (!isHash(oldHex) || !isHash(newHex) || !Array.isArray(proofHex)) return false;
  if (proofHex.length > 65) return false;
  for (const h of proofHex) if (!isHash(h)) return false;
  const oldRoot = Buffer.from(oldHex, 'hex');
  const newRoot = Buffer.from(newHex, 'hex');
  const proof = proofHex.map(h => Buffer.from(h, 'hex'));
  if (oldSize === 0n) {
    return proof.length === 0 && oldRoot.equals(EMPTY)
      && (newSize !== 0n || newRoot.equals(EMPTY));
  }
  if (oldSize === newSize) {
    return proof.length === 0 && oldRoot.equals(newRoot);
  }
  let pos = 0;
  function take() {
    if (pos >= proof.length) throw new Error('short proof');
    return proof[pos++];
  }
  function rebuild(m, n, known) {
    if (m === n) {
      const root = known ? oldRoot : take();
      return [root, root];
    }
    const k = split(n);
    if (m <= k) {
      const [oldLeft, newLeft] = rebuild(m, k, known);
      const right = take();
      return [oldLeft, node(newLeft, right)];
    }
    const [oldRight, newRight] = rebuild(m - k, n - k, false);
    const left = take();
    return [node(left, oldRight), node(left, newRight)];
  }
  try {
    const [a, b] = rebuild(oldSize, newSize, true);
    return pos === proof.length && a.equals(oldRoot) && b.equals(newRoot);
  } catch (error) {
    if (error.message === 'short proof') return false;
    throw error;
  }
}

const e = EMPTY.toString('hex');
const a = hash(Buffer.from([0]), Buffer.from('a')).toString('hex');
const b = hash(Buffer.from([0]), Buffer.from('b')).toString('hex');
console.log('zero-zero=' + verifyConsistency(0n,0n,e,e,[]));
console.log('zero-one=' + verifyConsistency(0n,1n,e,a,[]));
console.log('bad-empty-root=' + verifyConsistency(0n,1n,a,a,[]));
console.log('same-size=' + verifyConsistency(1n,1n,a,a,[]));
console.log('same-size-different-root=' + verifyConsistency(1n,1n,a,b,[]));
console.log('same-size-extra=' + verifyConsistency(1n,1n,a,a,[a]));
console.log('shrinking=' + verifyConsistency(2n,1n,a,a,[]));
console.log('zero-zero-wrong-new-root=' + verifyConsistency(0n,0n,e,a,[]));

精确输出:

zero-zero=true
zero-one=true
bad-empty-root=false
same-size=true
same-size-different-root=false
same-size-extra=false
shrinking=false
zero-zero-wrong-new-root=false

把这些分支写在算法入口处,比分散在哈希循环里更容易审查。尤其不要使用 oldSize 小于等于零时直接返回 true 的简写;负数不是空树,错误的空根也不是空树。对相同大小添加无用证明,本文也选择拒绝,保持可重复而严格的调用语义。

示例 8:格式验证必须发生在解码之前

Node.js 的十六进制解码并不保证替调用方严格拒绝所有非法文本;官方文档明确展示了非法字符或不完整字节导致截断的例子。因此先检查文本的完整长度与字符集,再交给 Buffer.from,不能反过来拿一次宽松解码当作验证。参见 Node.js Buffer 的十六进制编码说明。

数组也有一个容易漏掉的 JavaScript 细节:某些数组方法会跳过缺项。如果用 every 做验证却忽略稀疏数组的语义,空槽可能穿过第一层检查。本例使用 for...of 逐项检查,空槽会作为 undefined 被拒绝。我们同样拒绝超过长度上限的数组,并在任何递归或摘要拼接前完成这些检查。

保存为 08-malformed-inputs.cjs,执行 node 08-malformed-inputs.cjs。

'use strict';
const { createHash } = require('node:crypto');
const MAX_SIZE = (1n << 64n) - 1n;
const isSize = x => typeof x === 'bigint' && x >= 0n && x <= MAX_SIZE;
const isHash = x => typeof x === 'string' && /^[0-9a-fA-F]{64}$/.test(x);
const hash = (...parts) => createHash('sha256')
  .update(Buffer.concat(parts)).digest();
const EMPTY = hash(Buffer.alloc(0));
const node = (left, right) => hash(Buffer.from([1]), left, right);
function split(n) {
  let k = 1n;
  while (k * 2n < n) k *= 2n;
  return k;
}
function verifyConsistency(oldSize, newSize, oldHex, newHex, proofHex) {
  if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize) return false;
  if (!isHash(oldHex) || !isHash(newHex) || !Array.isArray(proofHex)) return false;
  if (proofHex.length > 65) return false;
  for (const h of proofHex) if (!isHash(h)) return false;
  const oldRoot = Buffer.from(oldHex, 'hex');
  const newRoot = Buffer.from(newHex, 'hex');
  const proof = proofHex.map(h => Buffer.from(h, 'hex'));
  if (oldSize === 0n) {
    return proof.length === 0 && oldRoot.equals(EMPTY)
      && (newSize !== 0n || newRoot.equals(EMPTY));
  }
  if (oldSize === newSize) {
    return proof.length === 0 && oldRoot.equals(newRoot);
  }
  let pos = 0;
  function take() {
    if (pos >= proof.length) throw new Error('short proof');
    return proof[pos++];
  }
  function rebuild(m, n, known) {
    if (m === n) {
      const root = known ? oldRoot : take();
      return [root, root];
    }
    const k = split(n);
    if (m <= k) {
      const [oldLeft, newLeft] = rebuild(m, k, known);
      const right = take();
      return [oldLeft, node(newLeft, right)];
    }
    const [oldRight, newRight] = rebuild(m - k, n - k, false);
    const left = take();
    return [node(left, oldRight), node(left, newRight)];
  }
  try {
    const [a, b] = rebuild(oldSize, newSize, true);
    return pos === proof.length && a.equals(oldRoot) && b.equals(newRoot);
  } catch (error) {
    if (error.message === 'short proof') return false;
    throw error;
  }
}
const oldHex = "36642e73c2540ab121e3a6bf9545b0a24982cd830eb13d3cd19de3ce6c021ec1";
const newHex = "4ae191939f548d9934740b88dea2c5cb89bb8870fc4505cd79dec6bbfaaee9cb";
const proofHex = [
  "597fcb31282d34654c200d3418fca5705c648ebf326ec73d8ddef11841f876d8",
  "d070dc5b8da9aea7dc0f5ad4c29d89965200059c9a0ceca3abd5da2492dcb71d",
  "b137985ff484fb600db93107c77b0365c80d78f5b429ded0fd97361d077999eb",
  "e286d3390665a7cdc759453bed0b00cded1842d757e3e6cfe87df53db177e725"
];

const check = (m,n,a,b,p) => verifyConsistency(m,n,a,b,p);
console.log('number-size=' + check(3,7n,oldHex,newHex,proofHex));
console.log('negative=' + check(-1n,7n,oldHex,newHex,proofHex));
console.log('overflow=' + check(3n,1n << 64n,oldHex,newHex,proofHex));
console.log('short-root=' + check(3n,7n,oldHex.slice(2),newHex,proofHex));
console.log('bad-hex=' + check(3n,7n,oldHex,newHex,['gg'.repeat(32)]));
console.log('sparse=' + check(3n,7n,oldHex,newHex,Array(4)));
console.log('too-many=' + check(3n,7n,oldHex,newHex,Array(66).fill(oldHex)));
console.log('uppercase=' + check(3n,7n,oldHex.toUpperCase(),newHex,proofHex));

精确输出:

number-size=false
negative=false
overflow=false
short-root=false
bad-hex=false
sparse=false
too-many=false
uppercase=true

最后一行允许大写十六进制,是明确选择的等价编码规则,而不是放宽摘要字节的含义。边界条件要写进接口契约:谁负责解析 JSON、谁把 base64 转换为字节、谁校验长度,都应有唯一责任方。本文用 hex 为了让示例可读,并未声称它就是 CT 网络响应的原始编码。

示例 9:用极大整数检查形状,但不伪装成真实日志

最后一段把旧大小设为 2 的 63 次方,新大小设为 uint64 最大值。它只构造两个合成子树承诺和一个组合根,用来测试大整数分割以及上界检查,不尝试分配这么多叶,也不声称这些摘要下面存在已展示的真实记录。这样的测试特别适合发现代码在某个分支偷偷转回 Number 的问题。

这里的大规模正例只有一个证明节点,因为旧大小正好是完整左子树的大小。边界覆盖还应包括非二次幂的旧大小和更长路径;本次独立评审测试另外使用不同算法与可高效构造的周期性叶树覆盖这些情况。大整数测试关注算法形状与输入约束,不能替代真实叶数据的互操作测试。

保存为 09-large-sizes.cjs,执行 node 09-large-sizes.cjs。

'use strict';
const { createHash } = require('node:crypto');
const MAX_SIZE = (1n << 64n) - 1n;
const isSize = x => typeof x === 'bigint' && x >= 0n && x <= MAX_SIZE;
const isHash = x => typeof x === 'string' && /^[0-9a-fA-F]{64}$/.test(x);
const hash = (...parts) => createHash('sha256')
  .update(Buffer.concat(parts)).digest();
const EMPTY = hash(Buffer.alloc(0));
const node = (left, right) => hash(Buffer.from([1]), left, right);
function split(n) {
  let k = 1n;
  while (k * 2n < n) k *= 2n;
  return k;
}
function verifyConsistency(oldSize, newSize, oldHex, newHex, proofHex) {
  if (!isSize(oldSize) || !isSize(newSize) || oldSize > newSize) return false;
  if (!isHash(oldHex) || !isHash(newHex) || !Array.isArray(proofHex)) return false;
  if (proofHex.length > 65) return false;
  for (const h of proofHex) if (!isHash(h)) return false;
  const oldRoot = Buffer.from(oldHex, 'hex');
  const newRoot = Buffer.from(newHex, 'hex');
  const proof = proofHex.map(h => Buffer.from(h, 'hex'));
  if (oldSize === 0n) {
    return proof.length === 0 && oldRoot.equals(EMPTY)
      && (newSize !== 0n || newRoot.equals(EMPTY));
  }
  if (oldSize === newSize) {
    return proof.length === 0 && oldRoot.equals(newRoot);
  }
  let pos = 0;
  function take() {
    if (pos >= proof.length) throw new Error('short proof');
    return proof[pos++];
  }
  function rebuild(m, n, known) {
    if (m === n) {
      const root = known ? oldRoot : take();
      return [root, root];
    }
    const k = split(n);
    if (m <= k) {
      const [oldLeft, newLeft] = rebuild(m, k, known);
      const right = take();
      return [oldLeft, node(newLeft, right)];
    }
    const [oldRight, newRight] = rebuild(m - k, n - k, false);
    const left = take();
    return [node(left, oldRight), node(left, newRight)];
  }
  try {
    const [a, b] = rebuild(oldSize, newSize, true);
    return pos === proof.length && a.equals(oldRoot) && b.equals(newRoot);
  } catch (error) {
    if (error.message === 'short proof') return false;
    throw error;
  }
}

// Abstract subtree commitments, not a materialized enormous log.
const left = hash(Buffer.from('synthetic-left'));
const right = hash(Buffer.from('synthetic-right'));
const oldHex = left.toString('hex');
const newHex = node(left,right).toString('hex');
const proofHex = [right.toString('hex')];
console.log('uint64-shape=' +
  verifyConsistency(1n << 63n,MAX_SIZE,oldHex,newHex,proofHex));
console.log('beyond-uint64=' +
  verifyConsistency(1n << 63n,MAX_SIZE + 1n,oldHex,newHex,proofHex));
console.log('exact-max-snapshot=' +
  verifyConsistency(MAX_SIZE,MAX_SIZE,newHex,newHex,[]));

精确输出:

uint64-shape=true
beyond-uint64=false
exact-max-snapshot=true

最后一行重复比较相同的最大大小快照,只验证相等分支可以处理这一整数。生产调用仍然必须传入经认证的快照;无论数值有多大,测试构造出来的根都不会自动变成可信日志头。

把 AI 代码审查落到可复现的验收条件

一份可接受的审查记录至少应说明四件事:输入语义是什么,返回 true 究竟确认了什么,哪些责任留在调用方,以及哪些负面用例真的执行过。对本文代码,核心确认只有在已指定大小和根之间,所给节点能依照树规则同时重建两端承诺,而且证明节点被完整消耗。签名、日志身份、首次信任、时间新鲜度、分叉视图发现以及记录的业务真实性,都需要相应的独立检查。

实际接入流程可以是:读取先前保存并认证过的检查点;获取并认证同日志的新检查点;使用两份已认证大小索取证明;执行一致性验证;在上层策略全部通过后,原子地保存新的检查点。并发更新时还要确认保存动作没有把另一个请求写入的较新检查点覆盖为较旧版本。验证失败时保留原状态和必要诊断证据,不因为服务端返回了更大的数字就自动前进。这里给出的是应用集成的检查思路,不是一个已经实现了持久化、网络错误恢复或并发控制的完整客户端。

发布前执行的独立测试共通过 835,749 条断言,覆盖零至一百二十八叶内的 8,385 个大小组合、2,172 个 uint64 范围树形,以及长度达到六十五节点的证明。九段示例还从 HTML 中重新提取并分别执行,输出与正文逐字一致。这个记录表示已执行测试的结果,不表示全部可能输入已经穷举,也不构成完整系统的安全认证。

测试方面,先用真实短列表覆盖各种树形,再让独立的迭代验证器核对递归版本,并加入极大整数、空树、相等大小、截断、尾随、换序、节点改写、格式错误及快照字段错配。特别要保留示例五:不是所有大小错配都由证明算法拒绝,这正是调用方必须认证大小的理由。测试通过可以提升对这些已覆盖行为的信心,但不能写成绝对安全、不可篡改或已经通过形式化验证。

审查 AI 输出的最后一步,不是赞叹代码很短,而是要求每个返回 true 都有准确而有限的解释。能把两个根、两个大小、证明结构和信任来源分别讲清楚,这段一致性验证代码才具备继续集成与评审的基础。

主要依据与复现说明

九个示例均为独立脚本,文中输出按对应脚本实际运行记录填写。代码没有请求生产日志、没有写入远端站点,也没有替调用方验证签名。概念图由图像模型独立生成,已经标注 AI概念图;它不参与算法说明或测试判定。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。