Skip to main content

Advanced Verification

Check balances, validator sets and blocks served by any Amadeus RPC against the validators' BLS quorum signatures and Merkle proofs, without running a node.

The Trustless Flow trusts whatever the RPC returns. This page shows how to check those answers yourself. The node serves four endpoints for this:

EndpointWhat it proves
GET /api/chain/consensus/<height>A quorum of validators signed the block hash and the state root of a finalized height
GET /api/proof/validator_record/<height>The validator set that takes over at <height>, proven against the state root of <height - 1>
GET /api/proof/contractstate/<key>A state value, such as a balance, proven against a state root
GET /api/proof/block/<height>A block is included in the chain's Merkle Mountain Range (MMR)

The trust chain goes: a validator set you trust, then the consensus that set signed, then the state root inside that consensus, then a value proven against that root. The samples below use the public mainnet RPC (https://mainnet-rpc.ama.one/api). They work against any node that serves these endpoints; block proofs need a node without pruning.

The TypeScript samples need the SDK and the two hashing libraries it is built on:

npm i @amadeus-protocol/sdk @noble/curves@1 @noble/hashes@1

What validators sign​

For every block they apply, validators sign a 104-byte claim:

entry_height (u64, big-endian) || entry_hash (32 bytes) || root_contractstate (32 bytes) || root_receipts (32 bytes)
  • root_contractstate is the root of the contract-state Merkle tree after the block. Every balance is a key in that tree.
  • root_receipts commits to the execution receipts of the block's transactions.

Each validator signs the claim bytes with BLS12-381, using the domain separation tag AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_ATTESTATION_. The node aggregates the signatures into one signature, plus a bitmask that says who signed. A claim is final when the signers make up at least 67% of the active validators (signers × 100 ≥ active × 67).

Get the consensus for a height​

/api/chain/consensus returns the consensus for the latest rooted (finalized) height. /api/chain/consensus/<height> returns it for a given height:

curl -s https://mainnet-rpc.ama.one/api/chain/consensus/90324025 | jq
{
"error": "ok",
"consensus": {
"aggsig": {
"mask": "2Kpitc3jt3dncJZ8CdrWR",
"mask_active": "8AQGAut7N92awznwCnjuQ",
"aggsig": "23gzdSjRjmJY5htMzqE3vQnpFJseETGvmqKeRUZBUrghRVebsJ75oNCD2fP36aJu4gYivVJwQDAiZaNYWgwNjdHHM35NBi2XJzYbZnR1nKSPZUBznpdg38V2F3GaR9rRpvuK"
},
"score": 0.8166666666666667,
"claim": "1111D8s7qYj4cf4RieD8xLDxTiNS1HuZJ9ShqbNJ3RwRgkTtMypvipMJPaBpTjWgwfn3K1wYG4nbMEFaMHaxppo6DZMiPz83xHQbVZ6Jer4rEg3ArcpMZ19dsdGy1AbdAZ8FmsB44dNE",
"root_contractstate": "Eeox7HRfswzYjCWLEzkk1LgTPKeTrJ3qc8gaxLjDGTZw",
"root_receipts": "A3A6766N2MqjcWCxDyUMfJ4VjweqpM9k73zXpjGKUwE6",
"claim_hash": "8rE51ZfsKX9yaPkozVRkDf4V6SaKsstPPxyQTFcjwcrM",
"entry_hash": "4aKWxhgAy496JdHPSUyTw9mKkheuSS8q5W4ET9YXySh9",
"entry_height": 90324025
}
}
  • claim is the signed 104-byte claim in Base58. entry_height, entry_hash, root_contractstate and root_receipts are its fields, decoded for convenience. claim_hash is its SHA-256.
  • aggsig.aggsig is the aggregate BLS signature (96 bytes). aggsig.mask has one bit per validator of the set, most significant bit first, set for each validator that signed. aggsig.mask_active marks the validators that were active.
  • score is signers divided by active validators.

A height that is not rooted yet, or that has no quorum, returns {"error":"not_found"}.

The JSON fields are a convenience. Only the claim bytes are signed, so a verifier checks that the fields match the claim, then checks the signature over the claim.

Know the validator set​

The set that signs a height is the latest validator record at or below that height. The chain writes a record in two cases: at the start of each epoch (heights that are multiples of 100,000) and in the block after a validator is slashed. A record is a contract-state value under the key bic:epoch:validators:height:<height, zero-padded to 12 digits>. Its value is VecPak-encoded: a map of validators (the 48-byte public keys, in mask order) and mask_active. Older records are a plain list of keys, all active; decodeValidatorSet below rejects them.

/api/proof/validator_record/<height> returns the record that takes effect at <height>, with a proof against the state root of the block before it:

curl -s https://mainnet-rpc.ama.one/api/proof/validator_record/90300000 \
| jq '.value |= (.[0:24] + "...") | .proof.siblings |= (.[0:1] + ["..."])'
{
"error": "ok",
"value": "C1PJzSFAuow7Y6ayG7jmuc1i...",
"key": "5tcP9uFhsZpBEvL7D8p3EqCuNYMsBTCA7u84JzMnDnv3nqNfUNVUKyZ",
"entry_hash": "4F1KbP3o6jfkdzkHqvQiJt4PF1zP7D6j1Lay1EhGr548",
"entry_height": 90299999,
"proof": {
"root": "7isT5vhnNbxc5Q6GtWBiaww5NCrjAND4hAuEpDyE4mYd",
"siblings": [
"46YX1gZAkQFgnMtRQPyRW1JqK3wCciS8of1Sm3BAV5Vz",
"..."
],
"terminus": {
"path": "GKSEBAz2dVHnWV4jLc4etUY69PgsbojaX4hpxqWs7JrH",
"value_hash": "3zxXXqubMRTxb8t1hhe5BdHwwSzyx5qr1AjwKZoqEvRQ",
"identity_hash": "HuxCZutjLxfxvp64XUFA4aJbAWfZZPxU7qQauYqJK5UC"
}
}
}

entry_height is <height> - 1, the block that wrote the record. The proof's root must equal the root_contractstate of /api/chain/consensus/90299999, and that consensus is signed by the previous set. So once you trust one set, you can verify each later set from the one before it. Heights without a record return {"error":"not_found"}.

The first set has to come from somewhere you already trust, for example the same endpoint on a node you run yourself.

Verify a consensus​

Save this module as consensus.ts. It decodes a validator record, and it accepts a consensus only when the claim matches its fields, the signers are active members of the set, they reach the 67% quorum, and the aggregate signature is valid:

import { decode, fromBase58, toBase58 } from '@amadeus-protocol/sdk'
import { bls12_381 as bls } from '@noble/curves/bls12-381'

const RPC = 'https://mainnet-rpc.ama.one/api'
const ATTESTATION_DST = 'AMADEUS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_ATTESTATION_'

export interface Consensus {
entry_height: number
entry_hash: string
root_contractstate: string
root_receipts: string
claim: string
aggsig: { aggsig: string; mask: string; mask_active: string }
}

export interface ValidatorSet {
validators: Uint8Array[]
maskActive: Uint8Array
}

const bitAt = (bytes: Uint8Array, index: number) => (bytes[index >> 3] >> (7 - (index & 7))) & 1
const popcount = (bytes: Uint8Array, size: number) =>
Array.from({ length: size }, (_unused, index) => bitAt(bytes, index)).reduce((sum, bit) => sum + bit, 0)

// Decodes the vecpak value served by /api/proof/validator_record/<height>
export function decodeValidatorSet(valueB58: string): ValidatorSet {
const decoded = decode(fromBase58(valueB58))
if (!(decoded instanceof Map)) throw new Error('unexpected validator record format')
const fields = new Map(
[...decoded].map(([key, value]) => [new TextDecoder().decode(key as Uint8Array), value])
)
return {
validators: fields.get('validators') as Uint8Array[],
maskActive: fields.get('mask_active') as Uint8Array
}
}

// Returns the consensus only if a 67% quorum of `set` signed its claim
export async function verifiedConsensus(height: number, set: ValidatorSet): Promise<Consensus> {
const response = await fetch(`${RPC}/chain/consensus/${height}`)
const body = (await response.json()) as { error: string; consensus?: Consensus }
if (body.error !== 'ok' || !body.consensus) throw new Error(`no consensus for ${height}: ${body.error}`)
const { consensus } = body

const claim = fromBase58(consensus.claim)
const claimHeight = new DataView(claim.buffer, claim.byteOffset).getBigUint64(0)
const claimMatches =
claim.length === 104 &&
claimHeight === BigInt(height) &&
toBase58(claim.slice(8, 40)) === consensus.entry_hash &&
toBase58(claim.slice(40, 72)) === consensus.root_contractstate &&
toBase58(claim.slice(72, 104)) === consensus.root_receipts
if (!claimMatches) throw new Error('claim does not match the consensus fields')

const rosterSize = set.validators.length
const mask = fromBase58(consensus.aggsig.mask)
if (consensus.aggsig.mask_active !== toBase58(set.maskActive)) throw new Error('mask_active mismatch')
const signedByInactive = set.validators.some(
(_pk, index) => bitAt(mask, index) === 1 && bitAt(set.maskActive, index) === 0
)
if (signedByInactive) throw new Error('inactive signer')
const signers = set.validators.filter((_pk, index) => bitAt(mask, index) === 1)
if (signers.length * 100 < popcount(set.maskActive, rosterSize) * 67) throw new Error('no quorum')

const signatureValid = bls.verify(
fromBase58(consensus.aggsig.aggsig),
claim,
bls.aggregatePublicKeys(signers),
{ DST: ATTESTATION_DST }
)
if (!signatureValid) throw new Error('invalid aggregate signature')
return consensus
}

Prove a balance​

A balance is stored under the key account: + the 48 raw public-key bytes + :balance:AMA (or another symbol). The value is the balance in flat units as a decimal string, for example 820000000 for 0.82 AMA. An address that never held the token has no key at all. An address that spent its whole balance keeps the key, with the value 0.

Request the proof with the whole key, Base58-encoded:

curl -s https://mainnet-rpc.ama.one/api/proof/contractstate/DjzF4AgZzHtFfap6hZUKCaVmziaCEhUZ5khWM2SAEb5ohpVVDUtR7G9n3gzowAh3gNqv64D2jDAXb8R1mza2cpfjg1oEg \
| jq '.proofs[0].proof.siblings |= (.[0:2] + ["..."])'
{
"error": "ok",
"root_contractstate": "GMowvnVaEwjJeCCh88hBXK2uqRaFjn5e74rzbUSavz5L",
"entry_hash": "FJpdFHLcCU3hUFUEHb6jgL6w1FHF4emZgid2yNUGiAAK",
"entry_height": 90324833,
"proofs": [
{
"key": "DjzF4AgZzHtFfap6hZUKCaVmziaCEhUZ5khWM2SAEb5ohpVVDUtR7G9n3gzowAh3gNqv64D2jDAXb8R1mza2cpfjg1oEg",
"proof": {
"root": "GMowvnVaEwjJeCCh88hBXK2uqRaFjn5e74rzbUSavz5L",
"siblings": [
"BgGNGzs1Z4Q2cpLzmVAPZpW5ZmY2dBcG3TJ2LTN3Ha4U",
"jR7cYXprBZzRQFo8VgVS28oMfYJoP5H3bhrRpdXkdwt",
"..."
],
"terminus": {
"path": "GRfEXzHQEX7kBmjMY4Q9WJssPn8Eyg5txJJb4tqaDfQ2",
"value_hash": "6YDbfUr7fCepAkUsTzwqESzKNNMdb2JgaMgRs2uCffNg",
"identity_hash": "8ZKDpevrAQgdee4FsWQwQ2ZPCjm5xhNwBvZ9MQaD7xos"
}
},
"namespace": "3dyEfi4rfUS9CaeMsySZeuSkRsA1ErRupaen8wpBrHLdzLyktHpGfKbs7FepK7TPxDudsGuugWcKQ"
}
]
}

The proof is built at the node's current tip (entry_height). Fetch /api/chain/consensus/<entry_height> to get the signed root_contractstate for that height. The tip is usually not rooted yet, so that call often answers not_found at first; retry it every half second until the height is rooted (verify-balance.ts below does this).

To prove up to 100 keys at once, all from the same tip, POST /api/proof/contractstate with a VecPak body {keys: [key, ...]} (raw key bytes). With the SDK, the body is encode({ keys }).

How the proof is checked​

The state is a sparse Merkle tree with 256-bit paths. All hashes are SHA-256:

  • Namespace: account: + the public key for account:<pk>:... keys, coin for coin:... keys, bic for bic:... keys, and the empty string for any other key. The response's namespace field is this value in Base58 (null for none).
  • Path: the first 4 bytes of sha256(namespace) followed by the first 28 bytes of sha256(key).
  • Leaf: sha256("LEAF" || identity_hash || value_hash), where identity_hash = sha256("ID" || path || sha256(namespace) || sha256(key)) and value_hash = sha256("VAL" || value).
  • Inner node: sha256("NODE" || left || right). An empty subtree at depth 256 hashes to 32 zero bytes, and an empty subtree at depth d hashes to the node hash of two empty subtrees at depth d + 1.
  • The proof lists one sibling per depth, from the root down, and a terminus for the subtree where the descent stopped: "empty", or the one leaf in it with its path, identity_hash and value_hash. Rebuild the terminus subtree, hash upward with the siblings, taking bit d of the target path to choose left or right at depth d, and compare the result with the trusted root.
  • If the terminus leaf has your path and identity, the key exists, and its value_hash tells you whether the value matches. If the terminus is "empty", or a leaf with a different path or identity, the key does not exist.

Save this module as state-proof.ts:

import { fromBase58, toBase58 } from '@amadeus-protocol/sdk'
import { sha256 } from '@noble/hashes/sha2'

export interface StateProof {
root: string
siblings: string[]
terminus: 'empty' | { path: string; identity_hash: string; value_hash: string }
}

const encoder = new TextEncoder()
const tag = (text: string) => encoder.encode(text)
const concat = (...parts: Uint8Array[]) => {
const out = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0))
parts.reduce((offset, part) => {
out.set(part, offset)
return offset + part.length
}, 0)
return out
}
const nodeHash = (left: Uint8Array, right: Uint8Array) => sha256(concat(tag('NODE'), left, right))
const bitAt = (path: Uint8Array, depth: number) => (path[depth >> 3] >> (7 - (depth & 7))) & 1
const sameUpperBits = (left: Uint8Array, right: Uint8Array, depth: number) =>
Array.from({ length: depth }, (_unused, index) => index).every(
(index) => bitAt(left, index) === bitAt(right, index)
)

// empties[depth] is the hash of an empty subtree rooted at that depth
const empties = Array.from({ length: 256 })
.reduce<Uint8Array[]>((list) => [...list, nodeHash(list[list.length - 1], list[list.length - 1])], [new Uint8Array(32)])
.reverse()

export function balanceKey(address: string, symbol = 'AMA') {
const publicKey = fromBase58(address)
if (publicKey.length !== 48) throw new Error(`not a 48-byte public key: ${address}`)
const namespace = concat(tag('account:'), publicKey)
return { namespace, key: concat(namespace, tag(`:balance:${symbol}`)) }
}

// Pass `value` null to check that the key is absent
export function verifyStateProof(
expectedRootB58: string,
proof: StateProof,
namespace: Uint8Array,
key: Uint8Array,
value: Uint8Array | null
): 'included' | 'absent' | 'mismatch' {
const targetPath = concat(sha256(namespace).slice(0, 4), sha256(key).slice(0, 28))
const siblings = proof.siblings.map(fromBase58)
const stop = siblings.length
if (stop > 256) throw new Error('malformed proof')
const { terminus } = proof
const leafPath = terminus === 'empty' ? targetPath : fromBase58(terminus.path)
const stopHash =
terminus === 'empty'
? empties[stop]
: Array.from({ length: 256 - stop }, (_unused, index) => 255 - index).reduce(
(hash, depth) =>
bitAt(leafPath, depth) === 0
? nodeHash(hash, empties[depth + 1])
: nodeHash(empties[depth + 1], hash),
sha256(concat(tag('LEAF'), fromBase58(terminus.identity_hash), fromBase58(terminus.value_hash)))
)
const root = Array.from({ length: stop }, (_unused, index) => stop - 1 - index).reduce(
(hash, depth) =>
bitAt(targetPath, depth) === 0 ? nodeHash(hash, siblings[depth]) : nodeHash(siblings[depth], hash),
stopHash
)
if (toBase58(root) !== expectedRootB58) throw new Error('proof does not reach the trusted root')
if (!sameUpperBits(leafPath, targetPath, stop)) throw new Error('malformed proof')

const identity = sha256(concat(tag('ID'), targetPath, sha256(namespace), sha256(key)))
const isSameLeaf =
terminus !== 'empty' &&
terminus.path === toBase58(targetPath) &&
terminus.identity_hash === toBase58(identity)
if (!isSameLeaf) return value === null ? 'absent' : 'mismatch'
if (value === null) return 'mismatch'
return terminus.value_hash === toBase58(sha256(concat(tag('VAL'), value))) ? 'included' : 'mismatch'
}

Put it together​

Keep the validator set current by verifying each new record with the set before it (validator-set.ts):

import { fromBase58 } from '@amadeus-protocol/sdk'
import { decodeValidatorSet, verifiedConsensus, type ValidatorSet } from './consensus'
import { verifyStateProof, type StateProof } from './state-proof'

const RPC = 'https://mainnet-rpc.ama.one/api'

interface ValidatorRecordResponse {
error: string
entry_height: number
key: string
value: string
proof: StateProof
}

// Accepts the record written for `recordHeight` only if `currentSet` signed the state that holds it
export async function nextValidatorSet(currentSet: ValidatorSet, recordHeight: number): Promise<ValidatorSet> {
const response = await fetch(`${RPC}/proof/validator_record/${recordHeight}`)
const record = (await response.json()) as ValidatorRecordResponse
if (record.error !== 'ok') throw new Error(`no validator record at ${recordHeight}: ${record.error}`)

const key = fromBase58(record.key)
const expectedKey = `bic:epoch:validators:height:${String(recordHeight).padStart(12, '0')}`
if (new TextDecoder().decode(key) !== expectedKey) throw new Error('unexpected record key')

const anchor = await verifiedConsensus(record.entry_height, currentSet)
const namespace = new TextEncoder().encode('bic')
const status = verifyStateProof(anchor.root_contractstate, record.proof, namespace, key, fromBase58(record.value))
if (status !== 'included') throw new Error(`validator record not proven: ${status}`)
return decodeValidatorSet(record.value)
}

Then check that an address holds exactly the balance your ledger expects (verify-balance.ts). The result is included when the chain agrees, mismatch when it does not, and absent when the address never held AMA and you expected zero:

import { toBase58 } from '@amadeus-protocol/sdk'
import { verifiedConsensus, type Consensus, type ValidatorSet } from './consensus'
import { balanceKey, verifyStateProof, type StateProof } from './state-proof'

const RPC = 'https://mainnet-rpc.ama.one/api'

interface ContractStateProofResponse {
error: string
entry_height: number
root_contractstate: string
proofs: { key: string; namespace: string | null; proof: StateProof }[]
}

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

// The proof is built at the tip, which is usually rooted within a second
async function rootedConsensus(height: number, set: ValidatorSet, attemptsLeft = 10): Promise<Consensus> {
try {
return await verifiedConsensus(height, set)
} catch (error) {
const isNotRootedYet = error instanceof Error && error.message.endsWith(': not_found')
if (!isNotRootedYet || attemptsLeft <= 1) throw error
await sleep(500)
return rootedConsensus(height, set, attemptsLeft - 1)
}
}

// `expectedFlat` is the balance your ledger says the address holds, in flat units
export async function verifyBalance(trustedSet: ValidatorSet, address: string, expectedFlat: bigint) {
const { namespace, key } = balanceKey(address)
const response = await fetch(`${RPC}/proof/contractstate/${toBase58(key)}`)
const proofResponse = (await response.json()) as ContractStateProofResponse
if (proofResponse.error !== 'ok') throw new Error(`proof error: ${proofResponse.error}`)

const consensus = await rootedConsensus(proofResponse.entry_height, trustedSet)
const check = (value: Uint8Array | null) =>
verifyStateProof(consensus.root_contractstate, proofResponse.proofs[0].proof, namespace, key, value)
const status = check(new TextEncoder().encode(expectedFlat.toString()))
// A zero balance is either stored as "0" or has no key at all
const isNeverFunded = expectedFlat === 0n && status !== 'included' && check(null) === 'absent'
return { height: consensus.entry_height, status: isNeverFunded ? 'absent' : status }
}

Start from the latest validator record at or below the current height, taken from a source you trust. When a new record appears (each epoch start, or after a slash), move to it with nextValidatorSet:

import { decodeValidatorSet } from './consensus'
import { nextValidatorSet } from './validator-set'
import { verifyBalance } from './verify-balance'

// `value` of /api/proof/validator_record/90200000, read from a node you run
const epochSet = decodeValidatorSet('<validator_record_value_b58>')
const trustedSet = await nextValidatorSet(epochSet, 90300000)

const result = await verifyBalance(trustedSet, '<deposit_address_b58>', 820000000n)
console.log(result)
{ height: 90326701, status: 'included' }

Prove that a block is in the chain​

Every block is a leaf of a Merkle Mountain Range whose root, root_chain, is committed in each block header. /api/proof/block/<height> proves that the block at <height> is a leaf of the MMR. By default it proves against the latest rooted block. ?at_height=<H> proves against the MMR as it stood just before block H was applied, which is the state that block H's header commits to:

curl -s "https://mainnet-rpc.ama.one/api/proof/block/90323898?at_height=90324000" \
| jq '.siblings |= (.[0:1] + ["..."]) | .other_peaks |= (.[0:1] + ["..."])'
{
"height": 90323898,
"claim": "1111D8s4WsrmQewhKgNhCNjzQtqqDFF53XyBfUAP1eUdPKYNHZySMWsKKxuci4Uehwr29GQXFxTzDXKaV6EENBBmdbXo8DF8zNLtvfi873MtW7wk5Q82yWwNmHKsKrc4JDrjQLz9AbVN",
"chain_id": "HsFp8cZeFuPxBmJcjvfwYu9MqXZi8fW6XxecLfyHEqEY",
"root_chain": "hsCWtmXDT3CRMRq6Hmccqhh4bmrLL812uWQv9Ppfmv3",
"peak_pos": 8,
"siblings": [
"HUhduYZuYeYjBrgzEcR3UEAowLsxWJUqiznQB4ty5k4S",
"..."
],
"other_peaks": [
"AYj1V7oHyCWAXU8oah4FMTaDz5MsNscXzDhhKL6v1vMm",
"..."
],
"at_hash": "C3RrqVKS5FVGV6ojUnQuhpcT73mCUJ4ZKUy3k6FiBdoU",
"at_height": 90324000,
"block_hash": "9QDWVWaXxCbWGLACMvKpKfa6PxCiCXEMqibNPZ9Dam2h"
}

A successful response has no error field.

  • From the claim fork (height 88,100,000 on mainnet, 4,100,000 on testnet), the leaf is the SHA-256 of the block's 104-byte claim, which the response includes. Below the fork, the leaf is the block hash and claim is null.
  • Check that block_hash and height are the block you asked about, and, after the fork, that the claim starts with that height and hash.
  • root_chain is only the node's statement. Trust it only if it equals the root_chain in the header of the block at at_height (at_hash), taken from a header you have verified yourself. In node 1.6.5, the JSON block endpoints return header.root_chain as raw bytes rather than Base58, so read it from a node you run.

The node's own verifier, API.Proof.verify_block in ex/lib/api/api_proof.ex, shows how siblings, other_peaks, peak_pos and chain_id combine into the root.

Errors​

EndpointerrorMeaning
/api/chain/consensus/<height>not_foundThe height is not rooted yet, or the node has no quorum consensus for it
/api/proof/validator_record/<height>not_foundNo validator record was written at that height
/api/proof/contractstatestate_root_mismatchThe node's tree root did not match its stored state root; try again
/api/proof/block/<height>pruned_historyThe node has pruned history (pruned_below_height in the reply); only nodes without pruning serve block proofs
target_not_rootedThe block is above the rooted height
height_not_in_main_chainThere is no main-chain block at that height
out_of_rangeThe block is not below the chosen at_height
proof_too_costlyThe block's MMR peak has more than 65,536 leaves, so the node refuses to build the proof (for example height 80,000,000 today)
commitment_not_rootedat_height is above the rooted height
at_height_not_in_main_chain, snapshot_unavailableThe node cannot rebuild the MMR state at at_height