btcd
btcd copied to clipboard
How to use btcd/txscript to build a custom locking and unlocking script.
-
First, generate a P2SH multisig address including some custom content.
script := txscript.NewScriptBuilder() // custom content
script.AddOp(txscript.OP_HASH160) script.AddData(Hash_Preimage_R) script.AddOp(txscript.OP_EQUALVERIFY)
// standard content
script.AddOp(txscript.OP_2) script.AddData(aPubKey) script.AddData(bPubKey) script.AddOp(txscript.OP_2) script.AddOp(txscript.OP_CHECKMULTISIG) return script.Script()
Then got an address like 2Mv12R1VNdiSzeFiDxs2WVxeBZzTScrs8Q6
- Sent some test bitcoin to the address above.
- Construct a transaction with btcd/txscript and btcd/wire to spend a UTXO of the address above.
4. How to write the unlocking script?
Currently, I'm using txscript.SignTxOutput
reference from https://sourcegraph.com/github.com/btcsuite/btcd/-/blob/txscript/sign_test.go#L344
// signature ...
sigScript, err := txscript.SignTxOutput(&chaincfg.TestNet3Params,
tx, 0, scriptPkScript, txscript.SigHashAll,
mkGetKey(map[string]addressToKey{
address1.EncodeAddress(): {key1.PrivKey, true},
address2.EncodeAddress(): {key2.PrivKey, true},
}), mkGetScript(map[string][]byte{
scriptAddr.EncodeAddress(): custom_pkScript,
}), nil)
if err != nil {
fmt.Println("Sign has wrong : ", err)
return
}
tx.TxIn[0].SignatureScript = sigScript
- But got a error: Sign has wrong : can't sign unknown transactions
Anybody have some idea? Thank you very much!
read https://developer.bitcoin.org/devguide/transactions.html#p2pkh-script-validation to get the idea behind bitcoin script language, you should provide some op-codes result in true on stack after completely be doen.
import(
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
)
tx := wire.NewMsgTx(2)
tx.AddTxOut(wire.NewTxOut(int64(*outputvalueFlag*1e8), script()))
func script() ([]byte) {
script := txscript.NewScriptBuilder()
script.AddInt64(1)
script.AddData(bytes[0:65])
script.AddInt64(1)
script.AddOp(txscript.OP_CHECKMULTISIG)
return script.Script()
}