decred.org/dcrdex@v1.0.5/dex/networks/btc/test/compat.go (about) 1 // This code is available on the terms of the project LICENSE.md file, 2 // also available online at https://blueoakcouncil.org/license/1.0.0. 3 4 package test 5 6 import ( 7 "testing" 8 9 "decred.org/dcrdex/dex/networks/btc" 10 11 "github.com/btcsuite/btcd/chaincfg" 12 "github.com/btcsuite/btcd/txscript" 13 ) 14 15 // CompatibilityItems are a set of pubkey scripts and corresponding 16 // string-encoded addresses checked in CompatibilityTest. They should be taken 17 // from existing on-chain data. 18 type CompatibilityItems struct { 19 P2PKHScript []byte 20 PKHAddr string 21 P2WPKHScript []byte 22 WPKHAddr string 23 P2SHScript []byte 24 SHAddr string 25 P2WSHScript []byte 26 WSHAddr string 27 } 28 29 // CompatibilityCheck checks various scripts' compatibility with the Backend. 30 // If a fork's CompatibilityItems can pass the CompatibilityCheck, the node 31 // can likely use NewBTCClone to create a DEX-compatible backend. 32 func CompatibilityCheck(t *testing.T, items *CompatibilityItems, chainParams *chaincfg.Params) { 33 t.Helper() 34 checkAddr := func(pkScript []byte, addr string) { 35 _, addrs, _, err := txscript.ExtractPkScriptAddrs(pkScript, chainParams) 36 if err != nil { 37 t.Fatalf("ExtractPkScriptAddrs error: %v", err) 38 } 39 if len(addrs) == 0 { 40 t.Fatalf("no addresses extracted from script %x", pkScript) 41 } 42 if addrs[0].String() != addr { 43 t.Fatalf("address mismatch %s != %s", addrs[0].String(), addr) 44 } 45 if !addrs[0].IsForNet(chainParams) { 46 t.Fatalf("IsForNet rejected address %v for net %v", addrs[0], chainParams.Name) 47 } 48 } 49 50 // P2PKH 51 pkh := btc.ExtractPubKeyHash(items.P2PKHScript) 52 if pkh == nil { 53 t.Fatalf("incompatible P2PKH script") 54 } 55 checkAddr(items.P2PKHScript, items.PKHAddr) 56 57 // P2WPKH 58 // A clone doesn't necessarily need segwit, so a nil value here will skip 59 // the test. 60 if items.P2WPKHScript != nil { 61 scriptClass := txscript.GetScriptClass(items.P2WPKHScript) 62 if scriptClass != txscript.WitnessV0PubKeyHashTy { 63 t.Fatalf("incompatible P2WPKH script") 64 } 65 checkAddr(items.P2WPKHScript, items.WPKHAddr) 66 } 67 68 // P2SH 69 sh := btc.ExtractScriptHash(items.P2SHScript) 70 if sh == nil { 71 t.Fatalf("incompatible P2SH script") 72 } 73 checkAddr(items.P2SHScript, items.SHAddr) 74 75 // P2WSH 76 if items.P2WSHScript != nil { 77 scriptClass := txscript.GetScriptClass(items.P2WSHScript) 78 if scriptClass != txscript.WitnessV0ScriptHashTy { 79 t.Fatalf("incompatible P2WPKH script") 80 } 81 wsh := btc.ExtractScriptHash(items.P2WSHScript) 82 if wsh == nil { 83 t.Fatalf("incompatible P2WSH script") 84 } 85 checkAddr(items.P2WSHScript, items.WSHAddr) 86 } 87 }