区块链原理 / 系统课时
交易格式检查与有效性验证有何不同
交易格式检查与有效性验证有何不同
节点收到交易后,即使字段齐全、编码正确,也不能立刻写入账本:签名可能不属于发送方,账户可能没钱,交易也可能已被执行。本课用金额为 10 的转账说明格式检查、授权验证、状态约束与重复检测各自负责什么,并运行一个最小验证器。
学习目标
- 区分能否解析交易与能否接受交易。
- 按签名、重复记录和当前账本状态定位拒绝原因。
- 运行转账示例,验证拒绝分支不会修改余额或交易序号。
格式正确不等于交易有效
格式检查回答“这串数据是否符合交易的编码和字段规则”,例如可否解码、字段是否齐全、amount 是否为整数、签名字段是否具有预期长度。签名有 64 字节并不意味着签名真的有效。
有效性验证还需判断“这笔交易现在能否被执行”。以下以账户模型为例;发送方余额为 20,下一笔合法交易序号 nonce=0。
| 检查层 | 具体判定 | 不通过的例子 |
|---|---|---|
| 格式与编码 | 必需字段、类型、长度和序列化规则 | amount 是字符串 "10" |
| 授权与静态规则 | 公钥验签、金额必须大于 0 | 将已签金额 10 改成 11 |
| 当前状态与去重 | 余额、账户 nonce、已处理交易 ID | 余额 8 却转 10,或重复提交已确认交易 |
这里的 nonce 是账户的交易序号,不是工作量证明中的随机数;比特币采用 UTXO 模型,通常不检查账户 nonce。
节点如何逐层决定接收或拒绝
- 解析传输字节,检查字段、类型、长度及编码规范;失败即停止,不进入密码学计算。
- 使用发送方公钥验签;签名必须覆盖收款人、金额、nonce 等实际要执行的字段。
- 检查交易 ID 是否已经处理。相同交易再次广播可以被忽略,但不能在同一账本状态中重复记账。
- 根据当前账本判断金额是否为正、nonce 是否恰好等于下一序号,以及余额能否支付金额与适用手续费。
- 全部通过后才应用余额、nonce 和已处理记录的变化;区块验证还必须按区块内顺序逐笔更新临时状态。

这是一种便于观察的检查顺序,不是所有公链的固定实现顺序。部分节点会先查已见交易 ID 来节省验签开销,但不能因此跳过最终的有效性检查。
用可运行示例复现拒绝原因
下面是简化的账户账本:发送方标识直接采用 Ed25519 公钥的十六进制编码,待签名消息使用字段排序后的 JSON 字节;这不是比特币或以太坊的真实交易格式。使用 Python 3.10+,先执行 python -m pip install cryptography,将代码保存为 validate_tx.py,再执行 python validate_tx.py。
import hashlib
import json
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
SIGNED_FIELDS = ('sender', 'recipient', 'amount', 'nonce')
ALL_FIELDS = set(SIGNED_FIELDS) | {'signature'}
def signing_bytes(tx):
payload = {name: tx[name] for name in SIGNED_FIELDS}
return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8')
def is_hex(value, length):
return isinstance(value, str) and len(value) == length and all(c in '0123456789abcdef' for c in value)
def format_ok(tx):
return (type(tx) is dict and set(tx) == ALL_FIELDS
and is_hex(tx['sender'], 64)
and isinstance(tx['recipient'], str) and bool(tx['recipient'])
and type(tx['amount']) is int and type(tx['nonce']) is int
and is_hex(tx['signature'], 128))
def apply(tx, balances, next_nonce, confirmed):
if not format_ok(tx):
return '格式错误'
message = signing_bytes(tx)
signature = bytes.fromhex(tx['signature'])
try:
# 验签覆盖收款人、金额和 nonce;改动其中一项就需重新签名。
Ed25519PublicKey.from_public_bytes(bytes.fromhex(tx['sender'])).verify(signature, message)
except (InvalidSignature, ValueError):
return '签名失败'
txid = hashlib.sha256(message + signature).hexdigest()
if txid in confirmed:
return '重复交易'
if tx['amount'] <= 0:
return '金额无效'
if tx['nonce'] != next_nonce.get(tx['sender'], 0):
return 'nonce 不匹配'
if balances.get(tx['sender'], 0) < tx['amount']:
return '余额不足'
# 只在全部验证通过后变更账本;此处用内存字典模拟提交。
balances[tx['sender']] -= tx['amount']
balances[tx['recipient']] = balances.get(tx['recipient'], 0) + tx['amount']
next_nonce[tx['sender']] = tx['nonce'] + 1
confirmed.add(txid)
return '通过'
key = Ed25519PrivateKey.generate()
sender = key.public_key().public_bytes(
encoding=serialization.Encoding.Raw,
format=serialization.PublicFormat.Raw,
).hex()
def make_tx(amount, nonce):
tx = {'sender': sender, 'recipient': 'bob', 'amount': amount, 'nonce': nonce}
tx['signature'] = key.sign(signing_bytes(tx)).hex()
return tx
balances = {sender: 20, 'bob': 0}
next_nonce = {sender: 0}
confirmed = set()
good = make_tx(10, 0)
cases = [
('字段类型错误', dict(good, amount='10')),
('签名被替换', dict(good, signature='00' * 64)),
('首次提交', good),
('再次提交', good),
('余额不足', make_tx(15, 1)),
('序号跳跃', make_tx(1, 3)),
]
for title, tx in cases:
print(f'{title}:{apply(tx, balances, next_nonce, confirmed)}')
print('最终状态:发送方={},收款方={},下个nonce={}'.format(
balances[sender], balances['bob'], next_nonce[sender]))预期输出:
字段类型错误:格式错误
签名被替换:签名失败
首次提交:通过
再次提交:重复交易
余额不足:余额不足
序号跳跃:nonce 不匹配
最终状态:发送方=10,收款方=10,下个nonce=1只有首次提交改变状态:发送方从 20 减到 10,收款方从 0 增至 10,下一个 nonce 变为 1。即便签名完全正确,后续的余额不足或序号不匹配仍会拒绝交易,且不会扣款。
同一交易为何在不同节点得到不同结论
假设两笔交易都由同一账户签署,nonce 都为 0,金额分别为 10 和 15,而账户余额为 20。节点在尚未确定执行顺序时,可以分别检查签名与格式;但一旦第一笔被确认并使 nonce 变为 1,另一笔就不能在这一状态下继续执行。不能只靠交易本身的字节判断它始终有效。
诊断时先问“数据能不能按规则解析”,再问“是否获得合法授权”,最后对照该节点正在使用的账本状态和已处理记录。格式错误通常不会因余额变化而恢复;余额、nonce 或输入花费状态导致的拒绝,则必须结合具体账本高度重新判断。