bitcoincash 0.32.4

General purpose library for using and interoperating with Bitcoin Cash.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Token
//!
//! Primitives for CashTokens.
//!

use core::fmt;

use crate::{TokenID, consensus::{Encodable, Decodable, deserialize_partial}, VarInt, ScriptBuf};

use super::opcodes;

/// Used as the first byte of the "wrapped" scriptPubKey to determine whether the output has token data
pub const PREFIX_BYTE: u8 = opcodes::all::OP_SPECIAL_TOKEN_PREFIX.to_u8();

/// Maximum consensus-valid length of the NFT commitment blob (128 bytes as of the May 2026
/// network upgrade, previously 40).
///
/// This is a transaction-validation rule, not a parsing rule: like the reference
/// implementation, (de)serialization does not enforce it.
pub const MAX_CONSENSUS_COMMITMENT_LENGTH: usize = 128;

/// High-order nibble of the token `bitfield` byte.  Describes what the structure of the token data payload that follows
/// is. These bitpatterns are bitwise-OR'd together to describe the data that follows in the token data payload.
/// This nibble may not be 0 or may not have the `Reserved` bit set.
#[repr(u8)]
pub enum Structure {
    /// The payload encodes an amount of fungible tokens.
    HasAmount = 0x10,
    /// The payload encodes a non-fungible token.
    HasNFT = 0x20,
    /// The payload encodes a commitment-length and a commitment (HasNFT must also be set).
    HasCommitmentLength = 0x40,
    /// Reserved. Must be unset.
    Reserved = 0x80,
}

/// Values for the low-order nibble of the token `bitfield` byte.  Must be `None` (0x0) for pure-fungible tokens
/// Encodes the "permissions" that an NFT has.  Note that these 3 bitpatterns are the only acceptable values for this
/// nibble.
#[repr(u8)]
pub enum Capability {
    /// No capability – either a pure-fungible or a non-fungible token which is an immutable token.
    None = 0x00,
    /// The `mutable` capability – the encoded non-fungible token is a mutable token.
    Mutable = 0x01,
    /// The `minting` capability – the encoded non-fungible token is a minting token.
    Minting = 0x02,
}

/// An amount of fungible CashTokens.
///
/// Maintains the invariant `0 <= amount <= i64::MAX`, mirroring `SafeAmount` in the reference
/// implementation. A *serialized* amount must additionally be non-zero; zero is only the
/// in-memory representation of "no fungible tokens" (the `HasAmount` bit unset).
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde", try_from = "i64", into = "i64"))]
pub struct TokenAmount(i64);

impl TokenAmount {
    /// Zero fungible tokens ("no amount").
    pub const ZERO: TokenAmount = TokenAmount(0);
    /// The maximum token amount, `2^63 - 1`.
    pub const MAX: TokenAmount = TokenAmount(i64::MAX);

    /// Creates a `TokenAmount`, returning [`None`] if `n` is negative.
    pub const fn from_int(n: i64) -> Option<TokenAmount> {
        if n < 0 {
            None
        } else {
            Some(TokenAmount(n))
        }
    }

    /// Returns the amount as a plain integer.
    pub const fn to_int(self) -> i64 { self.0 }

    /// Checked addition. Returns [`None`] if the sum exceeds [`TokenAmount::MAX`].
    pub fn checked_add(self, other: TokenAmount) -> Option<TokenAmount> {
        self.0.checked_add(other.0).map(TokenAmount)
    }

    /// Checked subtraction. Returns [`None`] if the result would be negative.
    pub fn checked_sub(self, other: TokenAmount) -> Option<TokenAmount> {
        self.0.checked_sub(other.0).filter(|n| *n >= 0).map(TokenAmount)
    }
}

impl fmt::Display for TokenAmount {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) }
}

impl From<TokenAmount> for i64 {
    fn from(amount: TokenAmount) -> i64 { amount.0 }
}

impl TryFrom<i64> for TokenAmount {
    type Error = AmountOutOfRangeError;

    fn try_from(n: i64) -> Result<TokenAmount, Self::Error> {
        TokenAmount::from_int(n).ok_or(AmountOutOfRangeError { value: n })
    }
}

/// Error returned when constructing a [`TokenAmount`] from an integer outside the valid
/// range `0..=i64::MAX`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AmountOutOfRangeError {
    /// The invalid value.
    pub value: i64,
}

impl fmt::Display for AmountOutOfRangeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "token amount {} out of range 0..=2^63-1", self.value)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for AmountOutOfRangeError {}

/// Data that gets serialized/deserialized to/from a scriptPubKey in a transaction output prefixed with PREFIX_BYTE
///
/// Both [`Encodable`] and [`Decodable`] enforce the CashTokens encoding rules: the bitfield
/// must be valid (see [`OutputData::is_valid_bitfield`]), a present commitment may not be
/// empty and a present amount must be in `1..=2^63-1`. Note that infallible entry points
/// (e.g. [`crate::consensus::serialize`] and [`crate::Transaction::compute_txid`]) panic on
/// invalid token data; fallible ones (e.g. [`crate::TxOut`]'s `consensus_encode`) return an error.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(crate = "actual_serde"))]
pub struct OutputData {
    /// Token ID
    pub id: TokenID,
    /// Token bitfield byte. High order nibble is one of the Structure enum values and low order nibble is Capability.
    pub bitfield: u8,
    /// Token amount. Zero when the `HasAmount` bit is unset.
    pub amount: TokenAmount,
    /// NFT commitment
    pub commitment: Vec<u8>
}

/// Whether `bitfield` is a valid CashTokens bitfield byte.
fn is_valid_bitfield(bitfield: u8) -> bool {
    // At least 1 bit must be set in the structure nibble, but the Structure::Reserved bit must not be set.
    let structure = bitfield & 0xf0;
    if structure >= Structure::Reserved as u8 || structure == 0x00 {
        return false;
    }
    let has_nft = (bitfield & Structure::HasNFT as u8) != 0;
    let has_amount = (bitfield & Structure::HasAmount as u8) != 0;
    let has_commitment_length = (bitfield & Structure::HasCommitmentLength as u8) != 0;
    // Capability nibble > 2 is invalid (the only valid bit-patterns are 0x00, 0x01, 0x02).
    if (bitfield & 0x0f) > Capability::Minting as u8 {
        return false;
    }
    // A token prefix encoding no tokens (both HasNFT and HasAmount are unset) is invalid.
    if !has_nft && !has_amount {
        return false;
    }
    // A token prefix where HasNFT is unset must encode a Capability nibble of 0x00.
    if !has_nft && (bitfield & 0x0f) != 0 {
        return false;
    }
    // A token prefix encoding HasCommitmentLength without HasNFT is invalid.
    if !has_nft && has_commitment_length {
        return false;
    }
    true
}

impl OutputData {
    /// The payload encodes a commitment-length and a commitment (HasNFT must also be set).
    pub fn has_commitment_length(&self) -> bool {
        (self.bitfield & Structure::HasCommitmentLength as u8) != 0
    }

    /// The payload encodes an amount of fungible tokens.
    pub fn has_amount(&self) -> bool {
        (self.bitfield & Structure::HasAmount as u8) != 0
    }

    /// Get capability bitmask
    pub fn capability(&self) -> u8 {
        self.bitfield & 0x0f
    }

    /// If utxo has NFT
    pub fn has_nft(&self) -> bool {
        (self.bitfield & Structure::HasNFT as u8) != 0
    }

    /// If utxo has minting capable NFT
    pub fn is_minting_nft(&self) -> bool {
        self.has_nft() && ((self.capability() & Capability::Minting as u8) != 0)
    }

    /// Whether the bitfield byte is valid per the CashTokens specification.
    pub fn is_valid_bitfield(&self) -> bool {
        is_valid_bitfield(self.bitfield)
    }
}

impl Encodable for OutputData {
    fn consensus_encode<W: crate::io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, crate::io::Error> {
        use crate::io::{Error, ErrorKind};

        if !self.is_valid_bitfield() {
            return Err(Error::new(ErrorKind::InvalidData, "invalid token bitfield"));
        }
        let mut len = 0;
        len += self.id.consensus_encode(writer)?;
        len += self.bitfield.consensus_encode(writer)?;
        if self.has_commitment_length() {
            if self.commitment.is_empty() {
                return Err(Error::new(ErrorKind::InvalidData, "token commitment may not be empty"));
            }
            len += self.commitment.consensus_encode(writer)?;
        }
        if self.has_amount() {
            if self.amount == TokenAmount::ZERO {
                return Err(Error::new(ErrorKind::InvalidData, "serialized token amount may not be 0"));
            }
            len += VarInt(self.amount.to_int() as u64).consensus_encode(writer)?;
        }
        Ok(len)
    }
}

impl Decodable for OutputData {
    fn consensus_decode<R: crate::io::Read + ?Sized>(reader: &mut R) -> Result<Self, crate::consensus::encode::Error> {
        use crate::consensus::encode::Error;

        let id = TokenID::consensus_decode(reader)?;
        let bitfield = u8::consensus_decode(reader)?;
        if !is_valid_bitfield(bitfield) {
            return Err(Error::ParseFailed("invalid token bitfield"));
        }

        let commitment = if (bitfield & Structure::HasCommitmentLength as u8) != 0 {
            let commitment = Vec::<u8>::consensus_decode(reader)?;
            if commitment.is_empty() {
                return Err(Error::ParseFailed("token commitment may not be empty"));
            }
            commitment
        } else {
            vec![]
        };
        let amount = if (bitfield & Structure::HasAmount as u8) != 0 {
            let amount = VarInt::consensus_decode(reader)?.0;
            if amount == 0 {
                return Err(Error::ParseFailed("serialized token amount may not be 0"));
            }
            if amount > i64::MAX as u64 {
                return Err(Error::ParseFailed("token amount out of range"));
            }
            TokenAmount::from_int(amount as i64).expect("range checked above")
        } else {
            TokenAmount::ZERO
        };
        Ok(OutputData {
            id,
            bitfield,
            amount,
            commitment,
        })
    }
}

/// Given a real scriptPubKey and token data, wrap the scriptPubKey into the "script + token data" blob
/// (which gets serialized to where the old txn format scriptPubKey used to live).
///
/// Errors if `token_data` is present but invalid (see [`OutputData`] encoding rules).
pub fn wrap_scriptpubkey(scriptpubkey: ScriptBuf, token_data: &Option<OutputData>) -> Result<ScriptBuf, crate::io::Error> {
    match token_data {
        Some(data) => {
            let mut bytes = Vec::with_capacity(1 + 34 + data.commitment.len() + 9 + scriptpubkey.len());
            bytes.push(PREFIX_BYTE);
            data.consensus_encode(&mut bytes)?;
            bytes.extend_from_slice(scriptpubkey.as_bytes());
            Ok(ScriptBuf::from(bytes))
        }
        None => Ok(scriptpubkey)
    }
}

/// Splits a "script + token data" blob (as serialized where the old txn format scriptPubKey
/// used to live) into the real scriptPubKey and optional token data.
///
/// Mirrors the reference implementation: a scriptPubKey that starts with [`PREFIX_BYTE`] but
/// does not parse as valid token data is tolerated rather than rejected ("so that we don't
/// fork ourselves off the network" -- such outputs exist on-chain from before the CashTokens
/// activation). The blob is then returned unchanged, prefix byte included, with no token data;
/// use [`crate::TxOut::has_unparseable_token_data`] to detect this case.
pub fn unwrap_scriptpubkey(scriptpubkey: ScriptBuf) -> (ScriptBuf, Option<OutputData>) {
    if scriptpubkey.as_bytes().first() != Some(&PREFIX_BYTE) {
        return (scriptpubkey, None);
    }
    match deserialize_partial::<OutputData>(&scriptpubkey.as_bytes()[1..]) {
        Ok((output_data, consumed)) => {
            // Eat prefix + token data
            let remaining: Vec<u8> = scriptpubkey.as_bytes()[1 + consumed..].to_vec();
            (ScriptBuf::from(remaining), Some(output_data))
        }
        Err(_) => (scriptpubkey, None),
    }
}

#[cfg(test)]
mod test {
    use crate::hex::{DisplayHex, Case};

    use super::*;

    const ID: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

    fn unwrap_hex(payload_after_prefix_byte: &str) -> (ScriptBuf, Option<OutputData>) {
        let script = ScriptBuf::from_hex(&format!("ef{}", payload_after_prefix_byte)).unwrap();
        unwrap_scriptpubkey(script)
    }

    /// Decodes a token payload (the bytes following [`PREFIX_BYTE`]) directly.
    fn decode_payload(payload: &str) -> Result<OutputData, crate::consensus::encode::Error> {
        use crate::hex::FromHex;
        let bytes = Vec::<u8>::from_hex(payload).unwrap();
        deserialize_partial::<OutputData>(&bytes).map(|(data, _)| data)
    }

    /// Asserts `payload` is rejected as token data, and that the wrapped scriptPubKey form
    /// falls back to "no token data, blob kept verbatim" (PATFO tolerance, as the reference).
    fn assert_invalid(payload: &str) {
        assert!(decode_payload(payload).is_err(), "payload {} should not parse", payload);
        let script = ScriptBuf::from_hex(&format!("ef{}", payload)).unwrap();
        let (unwrapped, token_data) = unwrap_scriptpubkey(script.clone());
        assert_eq!(script, unwrapped);
        assert_eq!(None, token_data);
    }

    // Test vectors from https://github.com/bitjson/cashtokens/blob/master/test-vectors/token-prefix-valid.json

    #[test]
    fn test_vectors() {
        let prefix = "efaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1001".to_string();
        let other_payload = "f00d".to_string();

        let script = ScriptBuf::from_hex(&(prefix + &other_payload)).unwrap();
        let (unwrapped_script, token_data) = unwrap_scriptpubkey(script.clone());
        let token_data = token_data.unwrap();

        assert_eq!(other_payload, unwrapped_script.to_hex_string());
        assert_eq!(TokenAmount::from_int(1).unwrap(), token_data.amount);
        assert_eq!(ID, token_data.id.to_string());
        // Round-trips back to the same wrapped script.
        assert_eq!(script, wrap_scriptpubkey(unwrapped_script, &Some(token_data)).unwrap());

        let prefix = "efbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb7229ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccffffffffffffffff7f".to_string();
        let script = ScriptBuf::from_hex(&(prefix + &other_payload)).unwrap();
        let (unwrapped_script, token_data) = unwrap_scriptpubkey(script.clone());
        let token_data = token_data.unwrap();
        assert_eq!(other_payload, unwrapped_script.to_hex_string());
        assert_eq!(TokenAmount::MAX, token_data.amount);
        assert_eq!("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", token_data.id.to_string());
        assert_eq!("cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", token_data.commitment.to_hex_string(Case::Lower));
        assert!(token_data.is_minting_nft());
        assert_eq!(script, wrap_scriptpubkey(unwrapped_script, &Some(token_data)).unwrap());

        // Minimal immutable NFT: bitfield HasNFT only, no commitment, no amount.
        let (_, token_data) = unwrap_hex(&format!("{}20", ID));
        let token_data = token_data.unwrap();
        assert!(token_data.has_nft());
        assert!(!token_data.has_amount());
        assert_eq!(TokenAmount::ZERO, token_data.amount);

        // Combined fungible amount + NFT (bitfields 0x30, 0x31, 0x32).
        for (bitfield, minting) in [("30", false), ("31", false), ("32", true)] {
            let (_, token_data) = unwrap_hex(&format!("{}{}01", ID, bitfield));
            let token_data = token_data.unwrap();
            assert!(token_data.has_nft() && token_data.has_amount());
            assert_eq!(minting, token_data.is_minting_nft());
        }

        // Commitment of 253 bytes: exercises the fd-prefixed CompactSize length path. The
        // consensus length cap is validated outside the parser, so this must parse.
        let commitment = "cc".repeat(253);
        let (_, token_data) = unwrap_hex(&format!("{}60fdfd00{}", ID, commitment));
        assert_eq!(253, token_data.unwrap().commitment.len());
    }

    // Invalid prefixes as in https://github.com/bitjson/cashtokens/blob/master/test-vectors/token-prefix-invalid.json

    #[test]
    fn invalid_bitfield_rejected() {
        // Structure nibble 0x0.
        assert_invalid(&format!("{}00", ID));
        // Reserved structure bit set.
        assert_invalid(&format!("{}90{}", ID, "01"));
        // Capability nibble > 2.
        assert_invalid(&format!("{}23", ID));
        // Capability without HasNFT.
        assert_invalid(&format!("{}11{}", ID, "01"));
        // HasCommitmentLength without HasNFT.
        assert_invalid(&format!("{}50{}", ID, "01cc01"));
    }

    #[test]
    fn invalid_amount_rejected() {
        // Amount of zero.
        assert_invalid(&format!("{}10{}", ID, "00"));
        // Amount 2^63, just above the maximum of 2^63-1.
        assert_invalid(&format!("{}10{}", ID, "ff0000000000000080"));
        // Amount 2^64-1.
        assert_invalid(&format!("{}10{}", ID, "ffffffffffffffffff"));
        // Non-minimally encoded CompactSize amount (1 as 0xfd-prefixed).
        assert_invalid(&format!("{}10{}", ID, "fd0100"));
        // Maximum amount 2^63-1 is accepted.
        let (_, token_data) = unwrap_hex(&format!("{}10{}", ID, "ffffffffffffffff7f"));
        assert_eq!(TokenAmount::MAX, token_data.unwrap().amount);
    }

    #[test]
    fn invalid_commitment_rejected() {
        // HasNFT | HasCommitmentLength with a zero-length commitment.
        assert_invalid(&format!("{}60{}", ID, "00"));
        // Non-minimally encoded CompactSize commitment length (1 as 0xfd-prefixed).
        assert_invalid(&format!("{}60{}", ID, "fd0100cc"));
    }

    #[test]
    fn truncated_payload_rejected() {
        // Bare prefix byte.
        assert_invalid("");
        // Truncated token id.
        assert_invalid("aaaa");
        // Missing bitfield.
        assert_invalid(ID);
        // HasCommitmentLength but missing the length byte.
        assert_invalid(&format!("{}60", ID));
        // Commitment shorter than its declared length.
        assert_invalid(&format!("{}6002cc", ID));
        // HasAmount but missing the amount.
        assert_invalid(&format!("{}10", ID));
        // Truncated multi-byte amount.
        assert_invalid(&format!("{}10fd00", ID));
    }

    #[test]
    fn unparseable_prefix_txout_roundtrip() {
        use crate::consensus::{deserialize, serialize};
        use crate::{Amount, TxOut};

        // Invalid token payload (bitfield 0x00) behind the prefix byte: kept verbatim in the
        // scriptPubKey with no token data, and re-serializes to the identical bytes.
        let script = ScriptBuf::from_hex(&format!("ef{}00", ID)).unwrap();
        let txout = TxOut { value: Amount::from_sat(1000), script_pubkey: script.clone(), token: None };
        let bytes = serialize(&txout);
        let decoded: TxOut = deserialize(&bytes).unwrap();
        assert_eq!(txout, decoded);
        assert!(decoded.has_unparseable_token_data());
        assert_eq!(bytes, serialize(&decoded));
    }

    #[test]
    fn encode_validates() {
        let valid = OutputData {
            id: ID.parse().unwrap(),
            bitfield: Structure::HasNFT as u8 | Structure::HasCommitmentLength as u8,
            amount: TokenAmount::ZERO,
            commitment: vec![0xcc],
        };
        let mut sink = Vec::new();
        assert!(valid.consensus_encode(&mut sink).is_ok());

        // Invalid bitfield.
        let mut invalid = valid.clone();
        invalid.bitfield = 0x00;
        assert!(invalid.consensus_encode(&mut Vec::new()).is_err());

        // HasCommitmentLength with an empty commitment.
        let mut invalid = valid.clone();
        invalid.commitment = Vec::new();
        assert!(invalid.consensus_encode(&mut Vec::new()).is_err());

        // HasAmount with a zero amount.
        let mut invalid = valid;
        invalid.bitfield |= Structure::HasAmount as u8;
        assert!(invalid.consensus_encode(&mut Vec::new()).is_err());

        // The error propagates through wrap_scriptpubkey and TxOut encoding.
        assert!(wrap_scriptpubkey(ScriptBuf::new(), &Some(invalid.clone())).is_err());
        let txout = crate::TxOut {
            value: crate::Amount::from_sat(1000),
            script_pubkey: ScriptBuf::new(),
            token: Some(invalid),
        };
        assert!(txout.consensus_encode(&mut Vec::new()).is_err());
    }

    #[test]
    fn token_amount() {
        assert_eq!(None, TokenAmount::from_int(-1));
        assert_eq!(Err(AmountOutOfRangeError { value: -1 }), TokenAmount::try_from(-1));
        assert_eq!(Ok(TokenAmount::MAX), TokenAmount::try_from(i64::MAX));

        let one = TokenAmount::from_int(1).unwrap();
        assert_eq!(None, TokenAmount::MAX.checked_add(one));
        assert_eq!(Some(TokenAmount::MAX), TokenAmount::MAX.checked_sub(TokenAmount::ZERO));
        assert_eq!(None, TokenAmount::ZERO.checked_sub(one));
        assert_eq!(Some(TokenAmount::ZERO), one.checked_sub(one));
    }
}