_example_test.go raw

   1  package txscript_test
   2  
   3  import (
   4  	"encoding/hex"
   5  	"fmt"
   6  	
   7  	"github.com/p9c/p9/pkg/chain/config/netparams"
   8  	chainhash "github.com/p9c/p9/pkg/chainhash"
   9  	txscript "github.com/p9c/p9/pkg/txscript"
  10  	"github.com/p9c/p9/pkg/wire"
  11  	ecc "github.com/p9c/p9/pkg/ecc"
  12  	"github.com/p9c/p9/pkg/util"
  13  )
  14  
  15  // This example demonstrates creating a script which pays to a bitcoin address. It also prints the created script hex
  16  // and uses the DisasmString function to display the disassembled script.
  17  func ExamplePayToAddrScript() {
  18  	// Parse the address to send the coins to into a util.Address which is useful to ensure the accuracy of the address and determine the address type.  It is also required for the upcoming call to
  19  	// PayToAddrScript.
  20  	addressStr := "12gpXQVcCL2qhTNQgyLVdCFG2Qs2px98nV"
  21  	address, e := util.DecodeAddress(addressStr, &netparams.MainNetParams)
  22  	if e != nil {
  23  		return
  24  	}
  25  	// Create a public key script that pays to the address.
  26  	script, e := txscript.PayToAddrScript(address)
  27  	if e != nil {
  28  		return
  29  	}
  30  	fmt.Printf("Script Hex: %x\n", script)
  31  	disasm, e := txscript.DisasmString(script)
  32  	if e != nil {
  33  		return
  34  	}
  35  	fmt.Println("Script Disassembly:", disasm)
  36  	// Output:
  37  	// Script Hex: 76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac
  38  	// Script Disassembly: OP_DUP OP_HASH160 128004ff2fcaf13b2b91eb654b1dc2b674f7ec61 OP_EQUALVERIFY OP_CHECKSIG
  39  }
  40  
  41  // // This example demonstrates extracting information from a standard public key script.
  42  // func ExampleExtractPkScriptAddrs() {
  43  // 	// Start with a standard pay-to-pubkey-hash script.
  44  // 	scriptHex := "76a914128004ff2fcaf13b2b91eb654b1dc2b674f7ec6188ac"
  45  // 	script, e := hex.DecodeString(scriptHex)
  46  // 	if e != nil  {
  47  // 		L.Script// 		return
  48  // 	}
  49  // 	// Extract and print details from the script.
  50  // 	scriptClass, addresses, reqSigs, e := txscript.ExtractPkScriptAddrs(
  51  // 		script, &netparams.MainNetParams)
  52  // 	if e != nil  {
  53  // 		L.Script// 		return
  54  // 	}
  55  // 	fmt.Println("Script Class:", scriptClass)
  56  // 	fmt.Println("Addresses:", addresses)
  57  // 	fmt.Println("Required Signatures:", reqSigs)
  58  // 	// Output:
  59  // 	// Script Class: pubkeyhash
  60  // 	// Addresses: [12gpXQVcCL2qhTNQgyLVdCFG2Qs2px98nV]
  61  // 	// Required Signatures: 1
  62  // }
  63  
  64  // This example demonstrates manually creating and signing a redeem transaction.
  65  func ExampleSignTxOutput() {
  66  	// Ordinarily the private key would come from whatever storage mechanism is being used, but for this example just hard code it.
  67  	privKeyBytes, e := hex.DecodeString("22a47fa09a223f2aa079edf85a7c2" +
  68  		"d4f8720ee63e502ee2869afab7de234b80c",
  69  	)
  70  	if e != nil {
  71  		return
  72  	}
  73  	privKey, pubKey := ecc.PrivKeyFromBytes(ecc.S256(), privKeyBytes)
  74  	pubKeyHash := util.Hash160(pubKey.SerializeCompressed())
  75  	addr, e := util.NewAddressPubKeyHash(pubKeyHash,
  76  		&netparams.MainNetParams,
  77  	)
  78  	if e != nil {
  79  		return
  80  	}
  81  	// For this example, create a fake transaction that represents what would ordinarily be the real transaction that is being spent.  It contains a single output that pays to address in the amount of 1 DUO.
  82  	originTx := wire.NewMsgTx(wire.TxVersion)
  83  	prevOut := wire.NewOutPoint(&chainhash.Hash{}, ^uint32(0))
  84  	txIn := wire.NewTxIn(prevOut, []byte{txscript.OP_0, txscript.OP_0}, nil)
  85  	originTx.AddTxIn(txIn)
  86  	pkScript, e := txscript.PayToAddrScript(addr)
  87  	if e != nil {
  88  		return
  89  	}
  90  	txOut := wire.NewTxOut(100000000, pkScript)
  91  	originTx.AddTxOut(txOut)
  92  	originTxHash := originTx.TxHash()
  93  	// Create the transaction to redeem the fake transaction.
  94  	redeemTx := wire.NewMsgTx(wire.TxVersion)
  95  	// Add the input(s) the redeeming transaction will spend.  There is no signature script at this point since it hasn't been created or signed yet, hence nil is provided for it.
  96  	prevOut = wire.NewOutPoint(&originTxHash, 0)
  97  	txIn = wire.NewTxIn(prevOut, nil, nil)
  98  	redeemTx.AddTxIn(txIn)
  99  	// Ordinarily this would contain that actual destination of the funds, but for this example don't bother.
 100  	txOut = wire.NewTxOut(0, nil)
 101  	redeemTx.AddTxOut(txOut)
 102  	// Sign the redeeming transaction.
 103  	lookupKey := func(a util.Address) (*ecc.PrivateKey, bool, error) {
 104  		// Ordinarily this function would involve looking up the private key for the provided address, but since the only thing being signed in this example uses the address associated with the private key from above, simply return it with the compressed flag set since the address is using the associated compressed public key.
 105  		// NOTE: If you want to prove the code is actually signing the transaction properly, uncomment the following line which intentionally returns an invalid key to sign with, which in turn will result in a failure during the script execution when verifying the signature.
 106  		// privKey.D.SetInt64(12345)
 107  		//
 108  		return privKey, true, nil
 109  	}
 110  	// Notice that the script database parameter is nil here since it isn't used.  It must be specified when pay-to-script-hash transactions are being signed.
 111  	sigScript, e := txscript.SignTxOutput(&netparams.MainNetParams,
 112  		redeemTx, 0, originTx.TxOut[0].PkScript, txscript.SigHashAll,
 113  		txscript.KeyClosure(lookupKey), nil, nil,
 114  	)
 115  	if e != nil {
 116  		return
 117  	}
 118  	redeemTx.TxIn[0].SignatureScript = sigScript
 119  	// Prove that the transaction has been validly signed by executing the script pair.
 120  	flags := txscript.ScriptBip16 | txscript.ScriptVerifyDERSignatures |
 121  		txscript.ScriptStrictMultiSig |
 122  		txscript.ScriptDiscourageUpgradableNops
 123  	vm, e := txscript.NewEngine(originTx.TxOut[0].PkScript, redeemTx, 0,
 124  		flags, nil, nil, -1,
 125  	)
 126  	if e != nil {
 127  		return
 128  	}
 129  	if e := vm.Execute(); dbg.Chk(e) {
 130  		return
 131  	}
 132  	fmt.Println("Transaction successfully signed")
 133  	// Output:
 134  	// Transaction successfully signed
 135  }
 136