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
use std::io;

use ring::digest::{digest, SHA256};
use serde::{Deserialize, Serialize};

use crate::{avax, codec, ids, key, platformvm, secp256k1fx};

#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
pub struct Validator {
    pub validator: platformvm::Validator,
    pub subnet_id: ids::Id,
}

impl Default for Validator {
    fn default() -> Self {
        Self::default()
    }
}

impl Validator {
    pub fn default() -> Self {
        Self {
            validator: platformvm::Validator::default(),
            subnet_id: ids::Id::empty(),
        }
    }
}

/// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/vms/platformvm#Tx
/// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/vms/platformvm#UnsignedAddSubnetValidatorTx
/// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/vms/platformvm#UnsignedTx
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
pub struct Tx {
    /// The transaction ID is empty for unsigned tx
    /// as long as "avax.BaseTx.Metadata" is "None".
    /// Once Metadata is updated with signing and "Tx.Initialize",
    /// Tx.ID() is non-empty.
    pub unsigned_tx: avax::BaseTx,
    pub validator: Validator,
    pub subnet_auth_input: secp256k1fx::Input,
    pub creds: Vec<secp256k1fx::Credential>,
}

impl Default for Tx {
    fn default() -> Self {
        Self::default()
    }
}

impl Tx {
    pub fn default() -> Self {
        Self {
            unsigned_tx: avax::BaseTx::default(),
            validator: Validator::default(),
            subnet_auth_input: secp256k1fx::Input::default(),
            creds: Vec::new(),
        }
    }

    pub fn new(unsigned_tx: avax::BaseTx) -> Self {
        Self {
            unsigned_tx,
            ..Self::default()
        }
    }

    /// Returns the transaction ID.
    /// Only non-empty if the embedded metadata is updated
    /// with the signing process.
    pub fn tx_id(&self) -> ids::Id {
        if self.unsigned_tx.metadata.is_some() {
            let m = self.unsigned_tx.metadata.clone().unwrap();
            m.id
        } else {
            ids::Id::default()
        }
    }

    pub fn type_name() -> String {
        "platformvm.UnsignedAddSubnetValidatorTx".to_string()
    }

    pub fn type_id() -> u32 {
        *(codec::P_TYPES.get(&Self::type_name()).unwrap()) as u32
    }

    /// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/vms/platformvm#Tx.Sign
    /// ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/utils/crypto#PrivateKeyED25519.SignHash
    /// TODO: support ledger signing
    pub fn sign<T: key::SignOnly>(&mut self, signers: Vec<Vec<T>>) -> io::Result<()> {
        // marshal "unsigned tx" with the codec version
        let type_id = Self::type_id();
        let packer = self.unsigned_tx.pack(codec::VERSION, type_id)?;

        // "avalanchego" marshals the whole struct again for signed bytes
        // even when the underlying "unsigned_tx" is already once marshaled
        // ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/vms/platformvm#Tx.Sign
        //
        // reuse the underlying packer to avoid marshaling the unsigned tx twice
        // just marshal the next fields in the struct and pack them all together
        // in the existing packer
        let unsigned_tx_bytes = packer.take_bytes();
        packer.set_bytes(&unsigned_tx_bytes);

        // pack the second field "validator" in the struct
        packer.pack_bytes(self.validator.validator.node_id.as_ref())?;
        packer.pack_u64(self.validator.validator.start)?;
        packer.pack_u64(self.validator.validator.end)?;
        packer.pack_u64(self.validator.validator.weight)?;
        packer.pack_bytes(self.validator.subnet_id.as_ref())?;

        // pack the third field "subnet_auth" in the struct
        let subnet_auth_type_id = secp256k1fx::Input::type_id();
        packer.pack_u32(subnet_auth_type_id)?;
        packer.pack_u32(self.subnet_auth_input.sig_indices.len() as u32)?;
        for sig_idx in self.subnet_auth_input.sig_indices.iter() {
            packer.pack_u32(*sig_idx)?;
        }

        // take bytes just for hashing computation
        let unsigned_tx_bytes = packer.take_bytes();
        packer.set_bytes(&unsigned_tx_bytes);

        // compute sha256 for marshaled "unsigned tx" bytes
        // IMPORTANT: take the hash only for the type "platformvm.UnsignedAddValidatorTx" unsigned tx
        // not other fields -- only hash "platformvm.UnsignedAddValidatorTx.*" but not "platformvm.Tx.Creds"
        // ref. https://pkg.go.dev/github.com/ava-labs/avalanchego/vms/platformvm#UnsignedAddValidatorTx
        let hash: Vec<u8> = digest(&SHA256, &unsigned_tx_bytes).as_ref().into();

        // number of of credentials
        let creds_len = signers.len() as u32;
        // pack the fourth field in the struct
        packer.pack_u32(creds_len)?;

        // sign the hash with the signers (in case of multi-sig)
        // and combine all signatures into a secp256k1fx credential
        self.creds = Vec::new();
        for keys in signers.iter() {
            let mut sigs: Vec<Vec<u8>> = Vec::new();
            for k in keys.iter() {
                let sig = k.sign_ecdsa_recoverable(&hash);
                sigs.push(sig);
            }

            let mut cred = secp256k1fx::Credential::default();
            cred.signatures = sigs;

            // add a new credential to "Tx"
            self.creds.push(cred);
        }
        if creds_len > 0 {
            // pack each "cred" which is "secp256k1fx.Credential"
            // marshal type ID for "secp256k1fx.Credential"
            let cred_type_id = secp256k1fx::Credential::type_id();
            for cred in self.creds.iter() {
                // marshal type ID for "secp256k1fx.Credential"
                packer.pack_u32(cred_type_id)?;

                // marshal fields for "secp256k1fx.Credential"
                packer.pack_u32(cred.signatures.len() as u32)?;
                for sig in cred.signatures.iter() {
                    packer.pack_bytes(sig)?;
                }
            }
        }
        let signed_tx_bytes = packer.take_bytes();
        let tx_id: Vec<u8> = digest(&SHA256, &signed_tx_bytes).as_ref().into();

        // update "BaseTx.Metadata" with id/unsigned bytes/bytes
        // ref. "avalanchego/vms/platformvm.Tx.Sign"
        // ref. "avalanchego/vms/components/avax.BaseTx.Metadata.Initialize"
        self.unsigned_tx.metadata = Some(avax::Metadata {
            id: ids::Id::from_slice(&tx_id),
            unsigned_bytes: unsigned_tx_bytes.to_vec(),
            bytes: signed_tx_bytes.to_vec(),
        });

        Ok(())
    }
}

/// RUST_LOG=debug cargo test --package avalanche-types --lib -- platformvm::add_subnet_validator::test_add_subnet_validator_tx_serialization_with_one_signer --exact --show-output
#[test]
fn test_add_subnet_validator_tx_serialization_with_one_signer() {
    use crate::{
        ids::{node, short},
        key::hot,
    };
    use avalanche_utils::cmp;

    let mut tx = Tx {
        unsigned_tx: avax::BaseTx {
            network_id: 1000000,
            transferable_outputs: Some(vec![avax::TransferableOutput {
                asset_id: ids::Id::from_slice(&<Vec<u8>>::from([
                    0x88, 0xee, 0xc2, 0xe0, 0x99, 0xc6, 0xa5, 0x28, //
                    0xe6, 0x89, 0x61, 0x8e, 0x87, 0x21, 0xe0, 0x4a, //
                    0xe8, 0x5e, 0xa5, 0x74, 0xc7, 0xa1, 0x5a, 0x79, //
                    0x68, 0x64, 0x4d, 0x14, 0xd5, 0x47, 0x80, 0x14, //
                ])),
                transfer_output: Some(secp256k1fx::TransferOutput {
                    amount: 0x2c6874d5c56f500,
                    output_owners: secp256k1fx::OutputOwners {
                        locktime: 0x00,
                        threshold: 0x01,
                        addrs: vec![short::Id::from_slice(&<Vec<u8>>::from([
                            0x65, 0x84, 0x4a, 0x05, 0x40, 0x5f, 0x36, 0x62, 0xc1, 0x92, //
                            0x81, 0x42, 0xc6, 0xc2, 0xa7, 0x83, 0xef, 0x87, 0x1d, 0xe9, //
                        ]))],
                    },
                }),
                ..avax::TransferableOutput::default()
            }]),
            transferable_inputs: Some(vec![avax::TransferableInput {
                utxo_id: avax::UtxoId {
                    output_index: 0,
                    tx_id: ids::Id::from_slice(&<Vec<u8>>::from([
                        0xdd, 0x91, 0x70, 0x54, 0x1a, 0xf4, 0x4b, 0x08, //
                        0x54, 0x4d, 0xae, 0x2c, 0x5e, 0x6f, 0x2b, 0xd9, //
                        0x1e, 0xd4, 0x1e, 0x72, 0x22, 0x44, 0x73, 0x56, //
                        0x1f, 0x50, 0xe8, 0xeb, 0xfc, 0xba, 0x59, 0xb9, //
                    ])),
                    ..avax::UtxoId::default()
                },
                asset_id: ids::Id::from_slice(&<Vec<u8>>::from([
                    0x88, 0xee, 0xc2, 0xe0, 0x99, 0xc6, 0xa5, 0x28, //
                    0xe6, 0x89, 0x61, 0x8e, 0x87, 0x21, 0xe0, 0x4a, //
                    0xe8, 0x5e, 0xa5, 0x74, 0xc7, 0xa1, 0x5a, 0x79, //
                    0x68, 0x64, 0x4d, 0x14, 0xd5, 0x47, 0x80, 0x14, //
                ])),
                transfer_input: Some(secp256k1fx::TransferInput {
                    amount: 0x2c6874d5c663740,
                    sig_indices: vec![0],
                }),
                ..avax::TransferableInput::default()
            }]),
            ..avax::BaseTx::default()
        },
        validator: Validator {
            validator: platformvm::Validator {
                node_id: node::Id::from_slice(&<Vec<u8>>::from([
                    0xca, 0xc3, 0x1b, 0x23, 0x7f, 0x96, 0x40, 0xd5, 0x01, 0x11, //
                    0xbe, 0x86, 0xb9, 0x58, 0x73, 0x0a, 0xfb, 0x70, 0x5e, 0x0f, //
                ])),
                start: 0x623d424b,
                end: 0x641e6651,
                weight: 0x3e8,
            },
            subnet_id: ids::Id::from_slice(&<Vec<u8>>::from([
                0xdd, 0x91, 0x70, 0x54, 0x1a, 0xf4, 0x4b, 0x08, 0x54, 0x4d, //
                0xae, 0x2c, 0x5e, 0x6f, 0x2b, 0xd9, 0x1e, 0xd4, 0x1e, 0x72, //
                0x22, 0x44, 0x73, 0x56, 0x1f, 0x50, 0xe8, 0xeb, 0xfc, 0xba, //
                0x59, 0xb9,
            ])),
        },
        subnet_auth_input: secp256k1fx::Input {
            sig_indices: vec![0_u32],
        },
        ..Tx::default()
    };

    let test_key =
        hot::Key::from_private_key("PrivateKey-2kqWNDaqUKQyE4ZsV5GLCGeizE6sHAJVyjnfjXoXrtcZpK9M67")
            .expect("failed to load private key");
    let keys1: Vec<hot::Key> = vec![test_key.clone()];
    let keys2: Vec<hot::Key> = vec![test_key];
    let signers: Vec<Vec<hot::Key>> = vec![keys1, keys2];
    tx.sign(signers).expect("failed to sign");
    let tx_metadata = tx.unsigned_tx.metadata.clone().unwrap();
    let signed_bytes = tx_metadata.bytes;
    assert_eq!(
        tx.tx_id().to_string(),
        "2bAuXK8TGqehHQCSaFkg4tSf7BX91aXM4qP3vX2Y62d4hg22T5"
    );

    let expected_signed_bytes: &[u8] = &[
        // codec version
        0x00, 0x00, //
        //
        // platformvm.UnsignedAddSubnetValidatorTx type ID
        0x00, 0x00, 0x00, 0x0d, //
        //
        // network id
        0x00, 0x0f, 0x42, 0x40, //
        //
        // blockchain id
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
        0x00, 0x00, //
        //
        // outs.len()
        0x00, 0x00, 0x00, 0x01, //
        //
        // "outs[0]" TransferableOutput.asset_id
        0x88, 0xee, 0xc2, 0xe0, 0x99, 0xc6, 0xa5, 0x28, 0xe6, 0x89, //
        0x61, 0x8e, 0x87, 0x21, 0xe0, 0x4a, 0xe8, 0x5e, 0xa5, 0x74, //
        0xc7, 0xa1, 0x5a, 0x79, 0x68, 0x64, 0x4d, 0x14, 0xd5, 0x47, //
        0x80, 0x14, //
        //
        // NOTE: fx_id is serialize:"false"
        //
        // "outs[0]" secp256k1fx.TransferOutput type ID
        0x00, 0x00, 0x00, 0x07, //
        //
        // "outs[0]" TransferableOutput.out.secp256k1fx::TransferOutput.amount
        0x02, 0xc6, 0x87, 0x4d, 0x5c, 0x56, 0xf5, 0x00, //
        //
        // "outs[0]" TransferableOutput.out.secp256k1fx::TransferOutput.output_owners.locktime
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, //
        //
        // "outs[0]" TransferableOutput.out.secp256k1fx::TransferOutput.output_owners.threshold
        0x00, 0x00, 0x00, 0x01, //
        //
        // "outs[0]" TransferableOutput.out.secp256k1fx::TransferOutput.output_owners.addrs.len()
        0x00, 0x00, 0x00, 0x01, //
        //
        // "outs[0]" TransferableOutput.out.secp256k1fx::TransferOutput.output_owners.addrs[0]
        0x65, 0x84, 0x4a, 0x05, 0x40, 0x5f, 0x36, 0x62, 0xc1, 0x92, //
        0x81, 0x42, 0xc6, 0xc2, 0xa7, 0x83, 0xef, 0x87, 0x1d, 0xe9, //
        //
        // ins.len()
        0x00, 0x00, 0x00, 0x01, //
        //
        // "ins[0]" TransferableInput.utxo_id.tx_id
        0xdd, 0x91, 0x70, 0x54, 0x1a, 0xf4, 0x4b, 0x08, 0x54, 0x4d, //
        0xae, 0x2c, 0x5e, 0x6f, 0x2b, 0xd9, 0x1e, 0xd4, 0x1e, 0x72, //
        0x22, 0x44, 0x73, 0x56, 0x1f, 0x50, 0xe8, 0xeb, 0xfc, 0xba, //
        0x59, 0xb9, //
        //
        // "ins[0]" TransferableInput.utxo_id.output_index
        0x00, 0x00, 0x00, 0x00, //
        //
        // "ins[0]" TransferableInput.asset_id
        0x88, 0xee, 0xc2, 0xe0, 0x99, 0xc6, 0xa5, 0x28, 0xe6, 0x89, //
        0x61, 0x8e, 0x87, 0x21, 0xe0, 0x4a, 0xe8, 0x5e, 0xa5, 0x74, //
        0xc7, 0xa1, 0x5a, 0x79, 0x68, 0x64, 0x4d, 0x14, 0xd5, 0x47, //
        0x80, 0x14, //
        //
        // "ins[0]" secp256k1fx.TransferInput type ID
        0x00, 0x00, 0x00, 0x05, //
        //
        // "ins[0]" TransferableInput.input.secp256k1fx::TransferInput.amount
        0x02, 0xc6, 0x87, 0x4d, 0x5c, 0x66, 0x37, 0x40, //
        //
        // "ins[0]" TransferableInput.input.secp256k1fx::TransferInput.sig_indices.len()
        0x00, 0x00, 0x00, 0x01, //
        //
        // "ins[0]" TransferableInput.input.secp256k1fx::TransferInput.sig_indices[0]
        0x00, 0x00, 0x00, 0x00, //
        //
        // memo.len()
        0x00, 0x00, 0x00, 0x00, //
        //
        // Validator.validator.node_id
        0xca, 0xc3, 0x1b, 0x23, 0x7f, 0x96, 0x40, 0xd5, 0x01, 0x11, //
        0xbe, 0x86, 0xb9, 0x58, 0x73, 0x0a, 0xfb, 0x70, 0x5e, 0x0f, //
        //
        // Validator.validator.start
        0x00, 0x00, 0x00, 0x00, 0x62, 0x3d, 0x42, 0x4b, //
        //
        // Validator.validator.end
        0x00, 0x00, 0x00, 0x00, 0x64, 0x1e, 0x66, 0x51, //
        //
        // Validator.validator.weight
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xe8, //
        //
        // Validator.subnet_id
        0xdd, 0x91, 0x70, 0x54, 0x1a, 0xf4, 0x4b, 0x08, //
        0x54, 0x4d, 0xae, 0x2c, 0x5e, 0x6f, 0x2b, 0xd9, //
        0x1e, 0xd4, 0x1e, 0x72, 0x22, 0x44, 0x73, 0x56, //
        0x1f, 0x50, 0xe8, 0xeb, 0xfc, 0xba, 0x59, 0xb9, //
        //
        // "secp256k1fx.Input" type ID
        0x00, 0x00, 0x00, 0x0a, //
        //
        // "secp256k1fx.Input.sig_indices.len()"
        0x00, 0x00, 0x00, 0x01, //
        //
        // "secp256k1fx.Input.sig_indices[0]"
        0x00, 0x00, 0x00, 0x00,
        //
        //
        // number of of credentials (avax.Tx.creds.len())
        0x00, 0x00, 0x00, 0x02, //
        //
        //
        // NOTE: fx_id is serialize:"false"
        //
        // struct field type ID "fx::Credential.cred"
        // "secp256k1fx.Credential" type ID
        0x00, 0x00, 0x00, 0x09, //
        //
        // number of signers ("fx::Credential.cred.sigs.len()")
        0x00, 0x00, 0x00, 0x01, //
        //
        // first 65-byte signature
        0x12, 0x51, 0x43, 0xaf, 0xa0, 0xd1, 0x5b, 0xe6, 0x06, 0xe2, //
        0xc5, 0x50, 0xe1, 0x09, 0xac, 0x86, 0xcd, 0x55, 0x45, 0xeb, //
        0x86, 0x5d, 0x8e, 0x19, 0xf0, 0x37, 0x28, 0x62, 0x8e, 0xaf, //
        0xac, 0x52, 0x3a, 0x2c, 0xe3, 0xde, 0x22, 0xa1, 0x3d, 0x3b, //
        0xfb, 0x67, 0x2b, 0x03, 0xa8, 0x29, 0xd7, 0xbd, 0x1d, 0x10, //
        0x06, 0x34, 0xbd, 0x2b, 0x4a, 0xf5, 0x3d, 0xb9, 0x0d, 0x2a, //
        0x63, 0x71, 0x38, 0x5a, 0x00, //
        //
        // struct field type ID "fx::Credential.cred"
        // "secp256k1fx.Credential" type ID
        0x00, 0x00, 0x00, 0x09, //
        //
        // number of signers ("fx::Credential.cred.sigs.len()")
        0x00, 0x00, 0x00, 0x01, //
        //
        // second 65-byte signature
        0x12, 0x51, 0x43, 0xaf, 0xa0, 0xd1, 0x5b, 0xe6, 0x06, 0xe2, //
        0xc5, 0x50, 0xe1, 0x09, 0xac, 0x86, 0xcd, 0x55, 0x45, 0xeb, //
        0x86, 0x5d, 0x8e, 0x19, 0xf0, 0x37, 0x28, 0x62, 0x8e, 0xaf, //
        0xac, 0x52, 0x3a, 0x2c, 0xe3, 0xde, 0x22, 0xa1, 0x3d, 0x3b, //
        0xfb, 0x67, 0x2b, 0x03, 0xa8, 0x29, 0xd7, 0xbd, 0x1d, 0x10, //
        0x06, 0x34, 0xbd, 0x2b, 0x4a, 0xf5, 0x3d, 0xb9, 0x0d, 0x2a, //
        0x63, 0x71, 0x38, 0x5a, 0x00, //
    ];
    // for c in &signed_bytes {
    //     print!("{:#02x},", *c);
    // }
    assert!(cmp::eq_vectors(expected_signed_bytes, &signed_bytes));
}