thruput-json-rpc-server 0.43.0

Reusable JSON-RPC server layer for Thruput
Documentation
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
use sha2::Digest;
use thruput_json_rpc_types::{base58::Base58, transaction::TxHash};

use thruput_tx_validation::{NetworkConfigParams, check_transaction};

use crate::{ValidatedTransaction, error::RpcServerError};

/// The `signatures` field of `SignedTransaction`, decoded for validation only.
type SignaturesField = xdrs::VecM<thruput_xdr::transaction::DecoratedSignature>;

/// The `pubkey_claim_key` field of `SignedTransaction`, decoded for validation only.
type PubkeyClaimKeyField = Option<thruput_xdr::types::PublicKey>;

/// Compile-time guard tying the hand-decoded field types to the fields they
/// stand in for.
///
/// [`validate_raw_transaction_bytes`] hand-decodes the fields of
/// `SignedTransaction` rather than decoding the struct, so a change to a
/// field's type — including a tighter `VecM` bound — or a new field must fail
/// the build instead of silently letting the gateway accept what a
/// whole-struct decode would reject.
const _: fn(thruput_xdr::transaction::SignedTransaction) = |signed| {
    let thruput_xdr::transaction::SignedTransaction {
        tx: _,
        signatures,
        pubkey_claim_key,
    } = signed;
    let _: SignaturesField = signatures;
    let _: PubkeyClaimKeyField = pubkey_claim_key;
};

/// Validate and hash raw signed transaction XDR bytes.
///
/// The returned hash is SHA-256 over the inner `Transaction` only — the
/// signatures and the attached `pubkey_claim_key` are excluded, so re-signing
/// a transaction does not change its hash. Signatures are decoded to reject malformed input, but are *not*
/// cryptographically verified here; authorization is the node's job.
///
/// Accepts exactly what a whole-buffer `xdrs::txs::decode::<SignedTransaction>`
/// accepts: trailing bytes after the envelope are rejected. A
/// `pubkey_claim_key` must be present exactly when the auth claim is
/// `kPubkeySignature`.
///
/// A signed transaction that decodes completely but breaks an executor
/// pre-execution bound (see [`check_transaction`]) is rejected with
/// [`RpcServerError::TxInvalidDetailed`], which carries the violated bound
/// as structured error data. Framing errors come first, so that detail
/// always describes an otherwise well-formed request.
pub fn validate_raw_transaction_bytes(
    tx_bytes: Vec<u8>,
    params: &NetworkConfigParams,
) -> Result<ValidatedTransaction, RpcServerError> {
    if u32::try_from(tx_bytes.len()).is_err() {
        return Err(RpcServerError::TxInvalid("transaction too large".into()));
    }

    // `SignedTransaction` is `{ tx, signatures, pubkey_claim_key }`, so the inner `Transaction`
    // occupies a contiguous prefix of `tx_bytes`. Hash that prefix directly
    // instead of re-encoding the decoded value: it avoids an allocation on the
    // submit path, and it hashes exactly the bytes the client signed rather
    // than trusting XDR to round-trip bit-for-bit.
    //
    // This assumes TXS decoding stays canonical — non-zero padding is rejected,
    // so an accepted encoding is the only encoding of its value. Enabling the
    // `xdrs/permissive` feature would break that and make this hash disagree
    // with a re-encode; `prefix_hash_matches_reencoded_inner_transaction` below
    // is what catches it.
    let mut reader = xdrs::txs::buf_reader::BufReader::new(&tx_bytes);

    let tx: thruput_xdr::transaction::Transaction = xdrs::read_xdr(&mut reader)
        .map_err(|e| RpcServerError::TxInvalid(format!("invalid XDR: {e}")))?;
    let tx_end = reader.position();

    // Decode the signatures and claim key too, and reject trailing bytes, so
    // this accepts exactly what a whole-buffer
    // `xdrs::txs::decode::<SignedTransaction>` would have accepted. The types
    // must stay in step with the fields they stand in for; the compile-time
    // guard above enforces that.
    let _signatures: SignaturesField = xdrs::read_xdr(&mut reader)
        .map_err(|e| RpcServerError::TxInvalid(format!("invalid XDR: {e}")))?;
    let pubkey_claim_key: PubkeyClaimKeyField = xdrs::read_xdr(&mut reader)
        .map_err(|e| RpcServerError::TxInvalid(format!("invalid XDR: {e}")))?;
    if reader.remaining() > 0 {
        return Err(RpcServerError::TxInvalid(
            "invalid XDR: trailing bytes after signed transaction".into(),
        ));
    }
    // The node also checks that the key hashes to the claimed one; presence
    // is checked here so a client omitting or misplacing it learns why.
    let pubkey_claim = matches!(
        tx.auth_claim,
        thruput_xdr::auth_claim::AuthClaim::kPubkeySignature { .. }
    );
    if pubkey_claim != pubkey_claim_key.is_some() {
        return Err(RpcServerError::TxInvalid(if pubkey_claim {
            "pubkey signature claim requires pubkey_claim_key".into()
        } else {
            "pubkey_claim_key is only allowed with a pubkey signature claim".into()
        }));
    }

    check_transaction(&tx, params).map_err(RpcServerError::TxInvalidDetailed)?;

    let hash_bytes: [u8; 32] = sha2::Sha256::digest(&tx_bytes[..tx_end]).into();
    let hash = TxHash(Base58(thruput_xdr::types::SHA256Hash::from(hash_bytes)));

    Ok(ValidatedTransaction {
        bytes: tx_bytes,
        hash,
        block_expiry_height: tx.uniquifier.block_expiry_height,
    })
}

/// Signed-transaction fixtures shared by this crate's unit tests.
#[cfg(test)]
pub(crate) mod test_fixtures {
    use thruput_xdr::{contract::Contract, transaction::SignedTransaction};

    /// Canonical XDR/hash vector. Structurally valid with a stable hash, but
    /// not auth-valid against empty hogd-dev genesis.
    pub(crate) const CANONICAL_HASH_VECTOR_SIGNED_TX_XDR: &str = "\
bc10f38522c4e14265a1483af9e5375f5dea0e2c6bf25727ee8b429bf3c1a9b7\
000000000000000000000000000f42400000000000000000000f424000000000000000010000000000000001\
13df30e7ceeb7c4c78ba6287e9d8830cabf5a744f3d6be3139f2428d7bb4f9e7000000000000000000000001\
000000000000000041d0144af2776cae9804ed899018a6bc17a5705d74c84e02556b9695031c9d3fe2554e5c\
e62ceadc95ba43c4aa0884cd2f9ebea4e3845ef877761a6222e91f0d000000010000000050ec72dbafd4898c\
5df0e15ea6ba3e46240945b7210fe2d63dde1e896f42107a";

    /// Hash of the inner transaction of the canonical vector.
    pub(crate) const CANONICAL_HASH: &str =
        "319674d13f52cc88935d86c37bb2c87710c24a3371e74fbc1480fc960aebb808";

    /// The canonical vector, decoded.
    pub(crate) fn canonical_signed_transaction() -> SignedTransaction {
        let canonical = hex::decode(CANONICAL_HASH_VECTOR_SIGNED_TX_XDR)
            .expect("bug: canonical hash vector should be valid hex");
        xdrs::txs::decode(&canonical).expect("bug: canonical hash vector should decode")
    }

    /// The canonical vector with `contracts` attached in `contracts_to_deploy`.
    ///
    /// Built through the XDR types rather than by splicing hex so the fixture
    /// tracks the schema instead of hard-coded field offsets.
    pub(crate) fn signed_transaction_with_contracts(contracts: Vec<Contract>) -> SignedTransaction {
        let mut signed = canonical_signed_transaction();
        signed.tx.contracts_to_deploy = xdrs::VecM(contracts);
        signed
    }

    /// `signed_transaction_with_contracts`, encoded as raw signed-transaction bytes.
    pub(crate) fn signed_tx_bytes_with_contracts(contracts: Vec<Contract>) -> Vec<u8> {
        xdrs::txs::encode(&signed_transaction_with_contracts(contracts))
            .expect("bug: re-encoded signed tx should encode")
    }
}

#[cfg(test)]
mod tests {
    use thruput_json_rpc_types::error::TxInvalidDetail;
    use thruput_xdr::contract::{Contract, ContractBlob};
    use xdr_common::BytesM;

    use super::test_fixtures::{
        CANONICAL_HASH, CANONICAL_HASH_VECTOR_SIGNED_TX_XDR, canonical_signed_transaction,
        signed_tx_bytes_with_contracts,
    };
    use super::*;
    use thruput_xdr::contract::kDefaultMaxContractSizeBytes;

    fn canonical_bytes() -> Vec<u8> {
        hex::decode(CANONICAL_HASH_VECTOR_SIGNED_TX_XDR).expect("bug: fixture should be valid hex")
    }

    fn rv32(size: usize, fill: u8) -> Contract {
        Contract::kRv32 {
            rv32_contract: ContractBlob {
                data: BytesM(vec![fill; size]),
            },
        }
    }

    /// Re-encodes the canonical vector carrying `count` copies of its signature.
    ///
    /// Built through the XDR types rather than by splicing hex so the variants
    /// track the schema instead of hard-coded field offsets.
    fn signed_tx_with_signature_count(count: usize) -> Vec<u8> {
        let mut signed = canonical_signed_transaction();

        let signature = signed.signatures.0[0].clone();
        signed.signatures = xdrs::VecM(vec![signature; count]);

        xdrs::txs::encode(&signed).expect("bug: re-encoded signed tx should encode")
    }

    #[test]
    fn prefix_hash_matches_reencoded_inner_transaction() {
        // Differential check against the algorithm this replaced: decode the
        // whole struct and hash a re-encode of the inner tx. Pins the relation
        // rather than the constant, so a `SignedTransaction` layout change
        // fails with a diagnosis instead of an unexplained hash diff.
        for count in [0usize, 1, 2, 5] {
            let bytes = signed_tx_with_signature_count(count);
            let signed: thruput_xdr::transaction::SignedTransaction =
                xdrs::txs::decode(&bytes).expect("bug: re-encoded signed tx should decode");
            let reencoded = xdrs::txs::encode(&signed.tx).expect("bug: inner tx should encode");
            let expected: [u8; 32] = sha2::Sha256::digest(&reencoded).into();

            let validated = validate_raw_transaction_bytes(bytes, &NetworkConfigParams::default())
                .expect("bug: re-encoded signed tx should validate");

            assert_eq!(
                validated.hash.0.0.as_ref(),
                expected.as_slice(),
                "hashed prefix diverged from the canonical Transaction encoding \
                 at {count} signature(s); SignedTransaction layout may have changed"
            );
        }
    }

    #[test]
    fn signature_count_does_not_affect_the_hash() {
        // The hash covers the inner transaction only, so adding, removing, or
        // replacing signatures must leave it untouched.
        for count in [0usize, 1, 2, 5] {
            let validated = validate_raw_transaction_bytes(
                signed_tx_with_signature_count(count),
                &NetworkConfigParams::default(),
            )
            .expect("bug: re-encoded signed tx should validate");

            assert_eq!(
                hex::encode(validated.hash.0.0.as_ref()),
                CANONICAL_HASH,
                "hash changed at {count} signature(s)"
            );
        }
    }

    #[test]
    fn invalid_xdr_is_rejected() {
        let err = validate_raw_transaction_bytes(vec![0], &NetworkConfigParams::default())
            .expect_err("bug: invalid XDR should fail");

        assert!(matches!(err, RpcServerError::TxInvalid(_)));
    }

    #[test]
    fn exposes_block_expiry_height_from_decoded_transaction() {
        let tx = validate_raw_transaction_bytes(canonical_bytes(), &NetworkConfigParams::default())
            .expect("bug: canonical hash vector should validate as XDR");

        assert_eq!(*tx.block_expiry_height, 1_000_000);
    }

    #[test]
    fn computes_canonical_hash_from_inner_transaction() {
        let tx = validate_raw_transaction_bytes(canonical_bytes(), &NetworkConfigParams::default())
            .expect("bug: canonical hash vector should validate as XDR");

        assert_eq!(hex::encode(tx.hash.0.0.as_ref()), CANONICAL_HASH);
    }

    #[test]
    fn trailing_bytes_after_signed_transaction_are_rejected() {
        let mut bytes = canonical_bytes();
        bytes.push(0);
        let err = validate_raw_transaction_bytes(bytes, &NetworkConfigParams::default())
            .expect_err("bug: trailing bytes should be rejected");

        assert!(matches!(err, RpcServerError::TxInvalid(_)));
    }

    #[test]
    fn truncated_envelope_is_rejected() {
        // Drop 4 bytes off the trailing claim key, so the transaction prefix
        // and signatures still decode but the key runs short.
        let mut truncated = canonical_bytes();
        truncated.truncate(truncated.len() - 4);
        let err = validate_raw_transaction_bytes(truncated, &NetworkConfigParams::default())
            .expect_err("bug: a truncated envelope should be rejected");

        assert!(matches!(err, RpcServerError::TxInvalid(_)));
    }

    #[test]
    fn pubkey_claim_requires_its_claim_key() {
        let mut signed = canonical_signed_transaction();
        signed.pubkey_claim_key = None;
        let bytes = xdrs::txs::encode(&signed).unwrap();

        let err = validate_raw_transaction_bytes(bytes, &NetworkConfigParams::default())
            .expect_err("bug: a pubkey claim without its key should be rejected");

        assert_eq!(
            err,
            RpcServerError::TxInvalid("pubkey signature claim requires pubkey_claim_key".into())
        );
    }

    #[test]
    fn claim_key_is_rejected_without_a_pubkey_claim() {
        let mut signed = canonical_signed_transaction();
        signed.tx.auth_claim = thruput_xdr::auth_claim::AuthClaim::kSourceAddressAuthData {
            source_address_claim: thruput_xdr::auth_claim::AuthClaim_source_address_claim {
                allowed_keys: 1,
                required_weight: 1,
            },
        };
        let bytes = xdrs::txs::encode(&signed).unwrap();

        let err = validate_raw_transaction_bytes(bytes, &NetworkConfigParams::default())
            .expect_err("bug: a claim key without a pubkey claim should be rejected");

        assert_eq!(
            err,
            RpcServerError::TxInvalid(
                "pubkey_claim_key is only allowed with a pubkey signature claim".into()
            )
        );
    }

    #[test]
    fn bound_violation_is_rejected_with_structured_detail() {
        let params = NetworkConfigParams {
            max_new_contracts_per_tx: Some(1),
            ..NetworkConfigParams::default()
        };
        let bytes = signed_tx_bytes_with_contracts(vec![rv32(8, 1), rv32(8, 2)]);

        let err = validate_raw_transaction_bytes(bytes, &params)
            .expect_err("bug: two contracts should exceed a cap of one");

        assert_eq!(
            err,
            RpcServerError::TxInvalidDetailed(TxInvalidDetail::TooManyContracts {
                attached: 2,
                max: 1
            })
        );
    }

    #[test]
    fn framing_errors_are_reported_before_bound_violations() {
        // Structured bound detail is only useful for a request that is
        // otherwise well-formed; trailing garbage after the signatures must
        // surface as the framing error it is.
        let params = NetworkConfigParams {
            max_new_contracts_per_tx: Some(1),
            ..NetworkConfigParams::default()
        };
        let mut bytes = signed_tx_bytes_with_contracts(vec![rv32(8, 1), rv32(8, 2)]);
        bytes.push(0);

        let err = validate_raw_transaction_bytes(bytes, &params)
            .expect_err("bug: trailing bytes should be rejected");

        assert_eq!(
            err,
            RpcServerError::TxInvalid(
                "invalid XDR: trailing bytes after signed transaction".into()
            )
        );
    }

    #[test]
    fn oversized_contract_is_rejected_without_a_config_reading() {
        // No reading leaves the protocol's default cap in force.
        let bytes = signed_tx_bytes_with_contracts(vec![rv32(
            kDefaultMaxContractSizeBytes as usize + 1,
            1,
        )]);

        let err = validate_raw_transaction_bytes(bytes, &NetworkConfigParams::default())
            .expect_err("bug: oversized contract should be rejected");

        assert!(matches!(
            err,
            RpcServerError::TxInvalidDetailed(TxInvalidDetail::ContractTooLarge { index: 0, .. })
        ));
    }

    #[test]
    fn attached_contracts_within_bounds_still_hash_the_inner_transaction() {
        let params = NetworkConfigParams {
            max_new_contracts_per_tx: Some(2),
            ..NetworkConfigParams::default()
        };
        let signed = super::test_fixtures::signed_transaction_with_contracts(vec![rv32(8, 1)]);
        let bytes = xdrs::txs::encode(&signed).unwrap();
        let reencoded = xdrs::txs::encode(&signed.tx).unwrap();
        let expected: [u8; 32] = sha2::Sha256::digest(&reencoded).into();

        let validated = validate_raw_transaction_bytes(bytes, &params)
            .expect("bug: in-bounds attachments should validate");

        assert_eq!(validated.hash.0.0.as_ref(), expected.as_slice());
    }

    #[test]
    fn empty_input_is_rejected() {
        let err = validate_raw_transaction_bytes(vec![], &NetworkConfigParams::default())
            .expect_err("bug: empty input should fail XDR decode");

        assert!(matches!(err, RpcServerError::TxInvalid(_)));
    }
}