0

Using the Bitcoin crate, I'm trying to create a transaction programmatically in Rust that spends an output associated with a P2WPKH address. This is the relevant code snippet:

fn sign_transaction<SignFun>(
    own_public_key: &[u8],
    own_address: &Address,
    own_utxos: &[Utxo],
    mut transaction: Transaction,
    key_name: String,
    derivation_path: Vec<Vec<u8>>,
    signer: SignFun,
) -> Transaction
where
    SignFun: Fn(String, Vec<Vec<u8>>, Vec<u8>) -> Vec<u8>,
{

    let txclone = transaction.clone();
    let mut hash_cache = sighash::SighashCache::new(&txclone);
    for (index, input) in transaction.input.iter_mut().enumerate() {
        let value = get_value(input, own_utxos);    // Look up the value by finding the corresponding UTXO
        let sighash = hash_cache
            .segwit_signature_hash(index, &own_address.script_pubkey(), value, SIG_HASH_TYPE)
            .expect("Creating the segwit signature hash failed.");

        let signature = signer(key_name.clone(), derivation_path.clone(), sighash.to_vec()).await;

        // Convert signature to DER.
        let der_signature = sec1_to_der(signature);

        let mut sig_with_hashtype = der_signature;
        sig_with_hashtype.push(SIG_HASH_TYPE.to_u32() as u8);
        let witness_bytes = vec![sig_with_hashtype, own_public_key.to_vec()];
        input.witness = Witness::from_vec(witness_bytes);
    }

    transaction
}

When sending a signed transaction to my local Bitcoin node in RegTest mode, I get the following error:

error code: -26
error message:
non-mandatory-script-verify-flag (Signature must be zero for failed CHECK(MULTI)SIG operation)

I logged the following information:

  • Public key: 0377f5de845ac601f24e7cbf2e4abcc9e1040cd4ae971ecaa00837b1c74684e15b
  • Address: bcrt1qh3zle7xs34azdyycg8cpf9wx5nxjpcqyqv4eyc
  • Input spent with value: 625000000
  • Transaction to sign: 0100000001ceac446d9350730c2a886220bed7ae154ca3f717897819091d5e72dcd0f0895e00000 00000ffffffff0200e1f505000000001600148be949ae15ee4b5da9af0ce2bf8d3f3c43c582da26 dc4a1f00000000160014bc45fcf8d08d7a26909841f01495c6a4cd20e00400000000
  • Sighash: d7e5696f18363b58c84b8d57014d291c9f7ebbac562d219f7e7014b9a5685bbf
  • SEC1 signature: c10c09b210914e49f295c07c9f96352e085df9d2c4272292239445d6f89483bc64c9903bebaba4b bf998d217c80375c36b60b212a824b63435e30205b2ed5a6a
  • DER signature: 3045022100c10c09b210914e49f295c07c9f96352e085df9d2c4272292239445d6f89483bc02206 4c9903bebaba4bbf998d217c80375c36b60b212a824b63435e30205b2ed5a6a
  • DER signature with Sighash type: 3045022100c10c09b210914e49f295c07c9f96352e085df9d2c4272292239445d6f89483bc02206 4c9903bebaba4bbf998d217c80375c36b60b212a824b63435e30205b2ed5a6a01
  • Signed transaction: 01000000000101ceac446d9350730c2a886220bed7ae154ca3f717897819091d5e72dcd0f0895e0 000000000ffffffff0200e1f505000000001600148be949ae15ee4b5da9af0ce2bf8d3f3c43c582 da26dc4a1f00000000160014bc45fcf8d08d7a26909841f01495c6a4cd20e00402483045022100c 10c09b210914e49f295c07c9f96352e085df9d2c4272292239445d6f89483bc022064c9903bebab a4bbf998d217c80375c36b60b212a824b63435e30205b2ed5a6a01210377f5de845ac601f24e7cb f2e4abcc9e1040cd4ae971ecaa00837b1c74684e15b00000000

Note that a similar piece of code for legacy (P2PKH) transactions using the same ECDSA signer works perfectly, so I'm assuming the signer is okay.

Any help to figure out where the problem lies would be greatly appreciated!

4
  • p2wpkh is weird -- the scriptCode is not the scriptPubKey but this weird sythetic pseudo-legacy scriptpubkey. See BIP 143 github.com/bitcoin/bips/blob/master/bip-0143.mediawiki and search "The item 5:". Sep 12, 2022 at 12:50
  • Thanks a lot for the tip! I wasn't aware of that. I'm not sure how the code needs to be updated, though. When printing out own_address.script_pubkey(), I get 0x0014{20-byte-pubkey-hash}. I changed it manually to 0x1976a914{20-byte-pubkey-hash}88ac based on the documentation you provided. I updated the witness_bytes in my code above providing these bytes instead but the transaction was still rejected. Next, I provided a script based on these bytes to segwit_signature_hash as well but that's not the solution, either. Any advice on how to update the code correctly?
    – THLO
    Sep 13, 2022 at 9:50
  • It's difficult to comment directly because your code doesn't work in isolation (e.g. I'd need to understand your signing logic) but in terms of general advice, I'd grab a known-working transaction off the blockchain and try to verify its signature with your logic. Once you've figured that out you have some assurance that your sighashing logic is alright and the problem lies elsewhere. Sep 15, 2022 at 0:01
  • Thanks for the suggestion. I currently don't have any signature verification logic. I just run the code against bitcoind, which worked nicely for P2PKH using the same signing logic as mentioned above. I think what would help the most is simply a working example for P2WPKH using the Bitcoin crate. My code is actually based on this implementation with all the deprecated parts updated. Unfortunately, I didn't find any code working with the current version of the crate.
    – THLO
    Sep 26, 2022 at 11:22

1 Answer 1

0

Even when the rawtransaction is right, if you give the wrong script_pubkey, it will generate wrong sighash. Just try to make sure that you are giving the right one. Try giving p2pkh script_pubkey of your pubkey.

let public_key = PublicKey::from_slice(own_public_key).unwrap();    
let script_code = bitcoin::Address::p2pkh(&public_key, bitcoin::network::constants::Network::Testnet).script_pubkey();
let sighash = hash_cache
        .segwit_signature_hash(index, &script_code, value, SIG_HASH_TYPE)
        .expect("Creating the segwit signature hash failed.");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.