arch_test_sdk 0.5.6

A Rust SDK for building applications on the Arch Network blockchain platform. Provides tools and interfaces for developing, testing, and deploying programs with native Bitcoin integration.
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
407
408
use std::time::Duration;
use std::{fs, str::FromStr};

use arch_program::{
    account::MIN_ACCOUNT_LAMPORTS, hash::Hash, pubkey::Pubkey, sanitized::ArchMessage,
    system_instruction, system_program::SYSTEM_PROGRAM_ID,
};
use arch_sdk::{
    build_and_sign_transaction, generate_new_keypair, AccountInfo, ArchRpcClient,
    ProcessedTransaction, ProgramDeployer, RuntimeTransaction, Status, {BitcoinHelper, Config},
};
use bitcoin::{
    absolute::LockTime,
    key::{Keypair, Secp256k1, TapTweak, TweakedKeypair},
    secp256k1::{self},
    sighash::{Prevouts, SighashCache},
    transaction::Version,
    Address, Amount, OutPoint, ScriptBuf, Sequence, TapSighashType, Transaction, TxIn, TxOut, Txid,
    Witness,
};
use bitcoincore_rpc::{Auth, Client, RawTx, RpcApi};

use crate::{
    constants::{
        BITCOIN_NETWORK, BITCOIN_NODE_ENDPOINT, BITCOIN_NODE_PASSWORD, BITCOIN_NODE_USERNAME,
        CALLER_FILE_PATH, NODE1_ADDRESS,
    },
    models::CallerInfo,
};

/* -------------------------------------------------------------------------- */
/*                             PREPARES A FEE PSBT                            */
/* -------------------------------------------------------------------------- */
/// This function sends the caller BTC, then prepares a fee PSBT and returns
/// the said PSBT in HEX encoding
pub fn prepare_fees() -> String {
    let userpass = Auth::UserPass(
        BITCOIN_NODE_USERNAME.to_string(),
        BITCOIN_NODE_PASSWORD.to_string(),
    );
    let rpc =
        Client::new(BITCOIN_NODE_ENDPOINT, userpass).expect("rpc shouldn not fail to be initiated");

    let caller = CallerInfo::with_secret_key_file(CALLER_FILE_PATH)
        .expect("getting caller info should not fail");

    let txid = rpc
        .send_to_address(
            &caller.address,
            Amount::from_sat(100000),
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .expect("SATs should be sent to address");

    let sent_tx = rpc
        .get_raw_transaction(&txid, None)
        .expect("should get raw transaction");
    let mut vout: u32 = 0;

    for (index, output) in sent_tx.output.iter().enumerate() {
        if output.script_pubkey == caller.address.script_pubkey() {
            vout = index as u32;
        }
    }

    let mut tx = Transaction {
        version: Version::TWO,
        input: vec![TxIn {
            previous_output: OutPoint { txid, vout },
            script_sig: ScriptBuf::new(),
            sequence: Sequence::MAX,
            witness: Witness::new(),
        }],
        output: vec![],
        lock_time: LockTime::ZERO,
    };

    let sighash_type = TapSighashType::NonePlusAnyoneCanPay;
    let raw_tx = rpc
        .get_raw_transaction(&txid, None)
        .expect("raw transaction should not fail");
    let prevouts = vec![raw_tx.output[vout as usize].clone()];
    let prevouts = Prevouts::All(&prevouts);

    let mut sighasher = SighashCache::new(&mut tx);
    let sighash = sighasher
        .taproot_key_spend_signature_hash(0, &prevouts, sighash_type)
        .expect("should not fail to construct sighash");

    // Sign the sighash using the secp256k1 library (exported by rust-bitcoin).
    let secp = Secp256k1::new();
    let tweaked: TweakedKeypair = caller.key_pair.tap_tweak(&secp, None);
    let msg = secp256k1::Message::from(sighash);
    let signature = secp.sign_schnorr(&msg, &tweaked.to_inner());

    // Update the witness stack.
    let signature = bitcoin::taproot::Signature {
        signature,
        sighash_type,
    };
    tx.input[0].witness.push(signature.to_vec());

    tx.raw_hex()
}

/* -------------------------------------------------------------------------- */
/*               PREPARES A FEE PSBT WITH EXTRA UTXO (RBF TESTS)              */
/* -------------------------------------------------------------------------- */
/// This function sends the caller BTC, then prepares a fee PSBT and returns
/// the said PSBT in HEX encoding
pub fn prepare_fees_with_extra_utxo(rune_txid: String, rune_vout: u32) -> String {
    let rune_txid = Txid::from_str(&rune_txid).unwrap();

    let userpass = Auth::UserPass(
        BITCOIN_NODE_USERNAME.to_string(),
        BITCOIN_NODE_PASSWORD.to_string(),
    );
    let rpc =
        Client::new(BITCOIN_NODE_ENDPOINT, userpass).expect("rpc shouldn not fail to be initiated");

    let caller = CallerInfo::with_secret_key_file(CALLER_FILE_PATH)
        .expect("getting caller info should not fail");

    let txid = rpc
        .send_to_address(
            &caller.address,
            Amount::from_sat(3000),
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .expect("SATs should be sent to address");

    let sent_tx = rpc
        .get_raw_transaction(&txid, None)
        .expect("should get raw transaction");
    let mut vout: u32 = 0;

    for (index, output) in sent_tx.output.iter().enumerate() {
        if output.script_pubkey == caller.address.script_pubkey() {
            vout = index as u32;
        }
    }

    let rune_sent_tx = rpc
        .get_raw_transaction(&rune_txid, None)
        .expect("should get raw transaction");

    let mut tx = Transaction {
        version: Version::TWO,
        input: vec![
            TxIn {
                previous_output: OutPoint {
                    txid: rune_txid,
                    vout: rune_vout,
                },
                script_sig: ScriptBuf::new(),
                sequence: Sequence::MAX,
                witness: Witness::new(),
            },
            TxIn {
                previous_output: OutPoint { txid, vout },
                script_sig: ScriptBuf::new(),
                sequence: Sequence::MAX,
                witness: Witness::new(),
            },
        ],
        output: vec![TxOut {
            value: rune_sent_tx.output[rune_vout as usize].value,
            script_pubkey: ScriptBuf::from_bytes(vec![]),
        }],
        lock_time: LockTime::ZERO,
    };

    // PREPARE Prevouts

    let rune_raw_tx = rpc
        .get_raw_transaction(&rune_txid, None)
        .expect("raw transaction should not fail");

    let raw_tx = rpc
        .get_raw_transaction(&txid, None)
        .expect("raw transaction should not fail");

    let prevouts = vec![
        rune_raw_tx.output[rune_vout as usize].clone(),
        raw_tx.output[vout as usize].clone(),
    ];
    let prevouts = Prevouts::All(&prevouts);

    // Sign rune input
    let rune_sighash_type = TapSighashType::SinglePlusAnyoneCanPay;

    let mut rune_sighasher = SighashCache::new(&mut tx);

    let rune_sighash = rune_sighasher
        .taproot_key_spend_signature_hash(0, &prevouts, rune_sighash_type)
        .expect("should not fail to construct sighash");

    let secp = Secp256k1::new();
    let tweaked: TweakedKeypair = caller.key_pair.tap_tweak(&secp, None);
    let msg = secp256k1::Message::from(rune_sighash);
    let rune_signature = secp.sign_schnorr(&msg, &tweaked.to_inner());

    let rune_signature = bitcoin::taproot::Signature {
        signature: rune_signature,
        sighash_type: rune_sighash_type,
    };

    tx.input[0].witness.push(rune_signature.to_vec());

    // Sign the anchoring utxo
    let sighash_type = TapSighashType::NonePlusAnyoneCanPay;

    let mut sighasher = SighashCache::new(&mut tx);

    let sighash = sighasher
        .taproot_key_spend_signature_hash(1, &prevouts, sighash_type)
        .expect("should not fail to construct sighash");

    // Sign the sighash using the secp256k1 library (exported by rust-bitcoin).
    let secp = Secp256k1::new();
    let tweaked: TweakedKeypair = caller.key_pair.tap_tweak(&secp, None);
    let msg = secp256k1::Message::from(sighash);
    let signature = secp.sign_schnorr(&msg, &tweaked.to_inner());

    // Update the witness stack.
    let signature = bitcoin::taproot::Signature {
        signature,
        sighash_type,
    };
    tx.input[1].witness.push(signature.to_vec());

    tx.raw_hex()
}

/* -------------------------------------------------------------------------- */
/*                     SENDS A UTXO TO THE ACCOUNT ADDRESS                    */
/* -------------------------------------------------------------------------- */
/// Used to send a utxo the taptweaked account address corresponding to the
/// network's joint pubkey
pub fn send_utxo(pubkey: Pubkey) -> (String, u32) {
    let bitcoin_config = Config::localnet();

    let bitcoin_helper = BitcoinHelper::new(&bitcoin_config);

    let (txid, vout) = bitcoin_helper.send_utxo(pubkey).unwrap();

    (txid, vout)
}

pub fn deploy_program(
    program_name: String,
    elf_path: String,
    program_keypair: Keypair,
    authority_keypair: Keypair,
) -> Pubkey {
    let deployer = ProgramDeployer::new(NODE1_ADDRESS, BITCOIN_NETWORK);

    deployer
        .try_deploy_program(program_name, program_keypair, authority_keypair, &elf_path)
        .unwrap()
}

pub fn deploy_program_elf(elf_path: String, program_keypair: Keypair, authority_keypair: Keypair) {
    let deployer = ProgramDeployer::new(NODE1_ADDRESS, BITCOIN_NETWORK);

    let elf = fs::read(elf_path).expect("elf path should be available");

    deployer
        .deploy_program_elf(program_keypair, authority_keypair, &elf)
        .unwrap();
}

pub fn create_account_with_anchor(
    from_pubkey: Pubkey,
    from_keypair: Keypair,
) -> (Keypair, Pubkey, Address) {
    let (account_key_pair, account_pubkey, address) = generate_new_keypair(BITCOIN_NETWORK);

    let (txid, vout) = send_utxo(account_pubkey);

    let arch_rpc_client = ArchRpcClient::new(NODE1_ADDRESS);

    let recent_blockhash = arch_rpc_client.get_best_finalized_block_hash().unwrap();
    let transaction = build_and_sign_transaction(
        ArchMessage::new(
            &[system_instruction::create_account_with_anchor(
                &from_pubkey,
                &account_pubkey,
                MIN_ACCOUNT_LAMPORTS,
                0,
                &SYSTEM_PROGRAM_ID,
                hex::decode(txid).unwrap().try_into().unwrap(),
                vout,
            )],
            Some(from_pubkey),
            recent_blockhash,
        ),
        vec![account_key_pair, from_keypair],
        BITCOIN_NETWORK,
    )
    .expect("Failed to build and sign transaction");

    let txid = arch_rpc_client
        .send_transaction(transaction)
        .expect("signing and sending a transaction should not fail");

    let processed_tx = arch_rpc_client
        .wait_for_processed_transaction(&txid)
        .expect("get processed transaction should not fail");

    assert!(matches!(processed_tx.status, Status::Processed));

    (account_key_pair, account_pubkey, address)
}

pub fn read_account_info(pubkey: Pubkey) -> AccountInfo {
    let arch_rpc_client = ArchRpcClient::new(NODE1_ADDRESS);
    // Retry with backoff to account for propagation/finality delays in CI
    let max_attempts: u32 = 50; // ~10s at 200ms per attempt
    let backoff = Duration::from_millis(200);

    for _attempt in 0..max_attempts {
        if let Ok(info) = arch_rpc_client.read_account_info(pubkey) {
            return info;
        }
        std::thread::sleep(backoff);
    }

    // Final attempt to surface the actual error in panic
    arch_rpc_client
        .read_account_info(pubkey)
        .expect("read account info should not fail after retries")
}

pub fn try_read_account_info(pubkey: Pubkey) -> Option<AccountInfo> {
    let arch_rpc_client = ArchRpcClient::new(NODE1_ADDRESS);

    arch_rpc_client.read_account_info(pubkey).ok()
}

pub fn send_transactions_and_wait(
    transactions: Vec<RuntimeTransaction>,
) -> Vec<ProcessedTransaction> {
    let arch_rpc_client = ArchRpcClient::new(NODE1_ADDRESS);
    let txids = arch_rpc_client.send_transactions(transactions).unwrap();

    arch_rpc_client
        .wait_for_processed_transactions(txids)
        .expect("get processed transactions should not fail")
}

/* -------------------------------------------------------------------------- */
/*                  ASSIGN AN ACCOUNT OWNERSHIP TO A PROGRAM                  */
/* -------------------------------------------------------------------------- */
/// Used to assign an account's ownership to another pubkey, requires current
/// owner's key pair.
pub fn assign_ownership_to_program(
    program_pubkey: Pubkey,
    account_to_transfer_pubkey: Pubkey,
    current_owner_keypair: Keypair,
) -> Hash {
    let arch_rpc_client = ArchRpcClient::new(NODE1_ADDRESS);

    let assign_instruction =
        system_instruction::assign(&account_to_transfer_pubkey, &program_pubkey);

    let current_owner_pubkey = Pubkey(current_owner_keypair.x_only_public_key().0.serialize());

    let recent_blockhash = arch_rpc_client.get_best_finalized_block_hash().unwrap();
    let transaction = build_and_sign_transaction(
        ArchMessage::new(
            &[assign_instruction],
            Some(current_owner_pubkey),
            recent_blockhash,
        ),
        vec![current_owner_keypair],
        BITCOIN_NETWORK,
    )
    .expect("Failed to build and sign transaction");

    let txid = arch_rpc_client
        .send_transaction(transaction)
        .expect("signing and sending a transaction should not fail");

    arch_rpc_client
        .wait_for_processed_transaction(&txid)
        .expect("get processed transaction should not fail");

    txid
}

pub fn create_and_fund_account_with_faucet(keypair: &Keypair, bitcoin_network: bitcoin::Network) {
    let arch_rpc_client = ArchRpcClient::new(NODE1_ADDRESS);

    arch_rpc_client
        .create_and_fund_account_with_faucet(keypair, bitcoin_network)
        .expect("create and fund account with faucet should not fail");
}