Skip to main content

ab_system_contract_simple_wallet_base/
seal.rs

1//! Utilities for [`Seal`] creation and verification
2
3use crate::{SIGNING_CONTEXT, Seal};
4use ab_contracts_common::ContractError;
5use ab_core_primitives::transaction::{
6    SerializedTransactionLengths, TransactionHeader, TransactionSlot,
7};
8use ab_io_type::trivial_type::TrivialType;
9use blake3::{Hasher, OUT_LEN};
10use core::mem::offset_of;
11use schnorrkel::context::SigningContext;
12use schnorrkel::{Keypair, PublicKey, Signature};
13
14/// Create transaction hash used for signing with [`sign()`].
15///
16/// The hash input is the serialized transaction (see [`Transaction::try_from_bytes()`]) with a
17/// [`Seal`] containing `nonce`, without the signature at the end of the seal.
18///
19/// [`hash_and_sign()`] helper function exists that combines this method with [`sign()`].
20///
21/// Returns `None` if there are more slots or payload bytes than [`SerializedTransactionLengths`]
22/// can describe, in which case it is not a transaction.
23///
24/// [`Transaction::try_from_bytes()`]: ab_core_primitives::transaction::Transaction::try_from_bytes
25// TODO: `no_panic` can't prove lack of panics in `blake3::Hasher` for input of arbitrary length
26// #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
27pub fn hash_transaction(
28    header: &TransactionHeader,
29    read_slots: &[TransactionSlot],
30    write_slots: &[TransactionSlot],
31    payload: &[u128],
32    nonce: u64,
33) -> Option<[u8; OUT_LEN]> {
34    const {
35        // Everything in the seal except the signature is signed, so the signature must be last
36        assert!(offset_of!(Seal, signature) + size_of::<[u8; 64]>() == size_of::<Seal>());
37    }
38
39    let lengths = SerializedTransactionLengths {
40        read_slots: u16::try_from(read_slots.len()).ok()?,
41        write_slots: u16::try_from(write_slots.len()).ok()?,
42        payload: u32::try_from(size_of_val(payload)).ok()?,
43        seal: Seal::SIZE,
44        padding: [0; _],
45    };
46
47    let mut hasher = Hasher::new();
48    hasher.update(header.as_bytes());
49    hasher.update(lengths.as_bytes());
50    hasher.update(TransactionSlot::slice_as_bytes(read_slots));
51    hasher.update(TransactionSlot::slice_as_bytes(write_slots));
52    hasher.update(u128::slice_as_bytes(payload));
53    let seal = Seal {
54        nonce,
55        signature: [0; _],
56    };
57    hasher.update(&seal.as_bytes()[..offset_of!(Seal, signature)]);
58    Some(hasher.finalize().into())
59}
60
61/// Sign transaction hash created with [`hash_transaction()`].
62///
63/// [`hash_and_sign()`] helper function exists that combines this method with
64/// [`hash_transaction()`].
65// TODO: `no_panic` can't prove lack of panics in `schnorrkel` signing
66// #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
67pub fn sign(keypair: &Keypair, tx_hash: &[u8; OUT_LEN]) -> Signature {
68    let signing_context = SigningContext::new(SIGNING_CONTEXT);
69    keypair.sign(signing_context.bytes(tx_hash))
70}
71
72/// Combines [`hash_transaction()`] and [`sign()`] and returns [`Seal`].
73///
74/// Returns `None` if [`hash_transaction()`] does.
75// TODO: `no_panic` can't prove lack of panics in `hash_transaction()` and `sign()`
76// #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
77pub fn hash_and_sign(
78    keypair: &Keypair,
79    header: &TransactionHeader,
80    read_slots: &[TransactionSlot],
81    write_slots: &[TransactionSlot],
82    payload: &[u128],
83    nonce: u64,
84) -> Option<Seal> {
85    let tx_hash = hash_transaction(header, read_slots, write_slots, payload, nonce)?;
86    let signature = sign(keypair, &tx_hash).to_bytes();
87
88    Some(Seal { nonce, signature })
89}
90
91/// Verify seal created by [`hash_and_sign()`].
92///
93/// [`hash_and_verify()`] helper function exists that combines this method with
94/// [`hash_transaction()`].
95// TODO: `no_panic` can't prove lack of panics in `schnorrkel` verification
96// #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
97pub fn verify(
98    public_key: &PublicKey,
99    expected_nonce: u64,
100    tx_hash: &[u8; OUT_LEN],
101    signature: &Signature,
102    nonce: u64,
103) -> Result<(), ContractError> {
104    if nonce != expected_nonce {
105        return Err(ContractError::BadInput);
106    }
107
108    let signing_context = SigningContext::new(SIGNING_CONTEXT);
109    public_key
110        .verify(signing_context.bytes(tx_hash.as_bytes()), signature)
111        .map_err(|_error| ContractError::Forbidden)
112}
113
114/// Combines [`hash_transaction()`] and [`verify()`].
115///
116/// Returns [`ContractError::BadInput`] if [`hash_transaction()`] returns `None`.
117// TODO: `no_panic` can't prove lack of panics in `hash_transaction()` and `schnorrkel` verification
118// #[cfg_attr(feature = "no-panic", no_panic_const::no_panic)]
119pub fn hash_and_verify(
120    public_key: &PublicKey,
121    expected_nonce: u64,
122    header: &TransactionHeader,
123    read_slots: &[TransactionSlot],
124    write_slots: &[TransactionSlot],
125    payload: &[u128],
126    seal: &Seal,
127) -> Result<(), ContractError> {
128    if seal.nonce != expected_nonce {
129        return Err(ContractError::BadInput);
130    }
131
132    let tx_hash = hash_transaction(header, read_slots, write_slots, payload, seal.nonce)
133        .ok_or(ContractError::BadInput)?;
134    let signature =
135        Signature::from_bytes(&seal.signature).map_err(|_error| ContractError::BadInput)?;
136
137    verify(public_key, expected_nonce, &tx_hash, &signature, seal.nonce)
138}