reference_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. // Copyright (c) 2013-2017 The btcsuite developers
  2. // Copyright (c) 2019 Caleb James DeLisle
  3. // Use of this source code is governed by an ISC
  4. // license that can be found in the LICENSE file.
  5. package txscript
  6. import (
  7. "bytes"
  8. "encoding/hex"
  9. "fmt"
  10. "io/ioutil"
  11. "strconv"
  12. "strings"
  13. "testing"
  14. jsoniter "github.com/json-iterator/go"
  15. "github.com/pkt-cash/pktd/btcutil/er"
  16. "github.com/pkt-cash/pktd/txscript/opcode"
  17. "github.com/pkt-cash/pktd/txscript/params"
  18. "github.com/pkt-cash/pktd/txscript/parsescript"
  19. "github.com/pkt-cash/pktd/txscript/scriptbuilder"
  20. "github.com/pkt-cash/pktd/txscript/txscripterr"
  21. "github.com/pkt-cash/pktd/wire/constants"
  22. "github.com/pkt-cash/pktd/btcutil"
  23. "github.com/pkt-cash/pktd/chaincfg/chainhash"
  24. "github.com/pkt-cash/pktd/chaincfg/globalcfg"
  25. "github.com/pkt-cash/pktd/wire"
  26. )
  27. // scriptTestName returns a descriptive test name for the given reference script
  28. // test data.
  29. func scriptTestName(test []interface{}) (string, er.R) {
  30. // Account for any optional leading witness data.
  31. var witnessOffset int
  32. if _, ok := test[0].([]interface{}); ok {
  33. witnessOffset++
  34. }
  35. // In addition to the optional leading witness data, the test must
  36. // consist of at least a signature script, public key script, flags,
  37. // and expected error. Finally, it may optionally contain a comment.
  38. if len(test) < witnessOffset+4 || len(test) > witnessOffset+5 {
  39. return "", er.Errorf("invalid test length %d", len(test))
  40. }
  41. // Use the comment for the test name if one is specified, otherwise,
  42. // construct the name based on the signature script, public key script,
  43. // and flags.
  44. var name string
  45. if len(test) == witnessOffset+5 {
  46. name = fmt.Sprintf("test (%s)", test[witnessOffset+4])
  47. } else {
  48. name = fmt.Sprintf("test ([%s, %s, %s])", test[witnessOffset],
  49. test[witnessOffset+1], test[witnessOffset+2])
  50. }
  51. return name, nil
  52. }
  53. // parse hex string into a []byte.
  54. func parseHex(tok string) ([]byte, er.R) {
  55. if !strings.HasPrefix(tok, "0x") {
  56. return nil, er.New("not a hex number")
  57. }
  58. x, e := hex.DecodeString(tok[2:])
  59. return x, er.E(e)
  60. }
  61. // parseWitnessStack parses a json array of witness items encoded as hex into a
  62. // slice of witness elements.
  63. func parseWitnessStack(elements []interface{}) ([][]byte, er.R) {
  64. witness := make([][]byte, len(elements))
  65. for i, e := range elements {
  66. witElement, err := hex.DecodeString(e.(string))
  67. if err != nil {
  68. return nil, er.E(err)
  69. }
  70. witness[i] = witElement
  71. }
  72. return witness, nil
  73. }
  74. // shortFormOps holds a map of opcode names to values for use in short form
  75. // parsing. It is declared here so it only needs to be created once.
  76. var shortFormOps map[string]byte
  77. // parseShortForm parses a string as as used in the Bitcoin Core reference tests
  78. // into the script it came from.
  79. //
  80. // The format used for these tests is pretty simple if ad-hoc:
  81. // - Opcodes other than the push opcodes and unknown are present as
  82. // either OP_NAME or just NAME
  83. // - Plain numbers are made into push operations
  84. // - Numbers beginning with 0x are inserted into the []byte as-is (so
  85. // 0x14 is OP_DATA_20)
  86. // - Single quoted strings are pushed as data
  87. // - Anything else is an error
  88. func parseShortForm(script string) ([]byte, er.R) {
  89. // Only create the short form opcode map once.
  90. if shortFormOps == nil {
  91. ops := make(map[string]byte)
  92. for opcodeName, opcodeValue := range OpcodeByName {
  93. if strings.Contains(opcodeName, "OP_UNKNOWN") {
  94. continue
  95. }
  96. ops[opcodeName] = opcodeValue
  97. // The opcodes named OP_# can't have the OP_ prefix
  98. // stripped or they would conflict with the plain
  99. // numbers. Also, since OP_FALSE and OP_TRUE are
  100. // aliases for the OP_0, and OP_1, respectively, they
  101. // have the same value, so detect those by name and
  102. // allow them.
  103. if (opcodeName == "OP_FALSE" || opcodeName == "OP_TRUE") ||
  104. (opcodeValue != opcode.OP_0 && (opcodeValue < opcode.OP_1 ||
  105. opcodeValue > opcode.OP_16)) {
  106. ops[strings.TrimPrefix(opcodeName, "OP_")] = opcodeValue
  107. }
  108. }
  109. shortFormOps = ops
  110. }
  111. // Split only does one separator so convert all \n and tab into space.
  112. script = strings.ReplaceAll(script, "\n", " ")
  113. script = strings.ReplaceAll(script, "\t", " ")
  114. tokens := strings.Split(script, " ")
  115. builder := scriptbuilder.NewScriptBuilder()
  116. for _, tok := range tokens {
  117. if tok == "" {
  118. continue
  119. }
  120. // if parses as a plain number
  121. if num, err := strconv.ParseInt(tok, 10, 64); err == nil {
  122. builder.AddInt64(num)
  123. continue
  124. } else if bts, err := parseHex(tok); err == nil {
  125. // Concatenate the bytes manually since the test code
  126. // intentionally creates scripts that are too large and
  127. // would cause the builder to error otherwise.
  128. if builder.ErrInt == nil {
  129. builder.ScriptInt = append(builder.ScriptInt, bts...)
  130. }
  131. } else if len(tok) >= 2 &&
  132. tok[0] == '\'' && tok[len(tok)-1] == '\'' {
  133. builder.AddFullData([]byte(tok[1 : len(tok)-1]))
  134. } else if opcode, ok := shortFormOps[tok]; ok {
  135. builder.AddOp(opcode)
  136. } else {
  137. return nil, er.Errorf("bad token %q", tok)
  138. }
  139. }
  140. return builder.Script()
  141. }
  142. // parseScriptFlags parses the provided flags string from the format used in the
  143. // reference tests into ScriptFlags suitable for use in the script engine.
  144. func parseScriptFlags(flagStr string) (ScriptFlags, er.R) {
  145. var flags ScriptFlags
  146. sFlags := strings.Split(flagStr, ",")
  147. for _, flag := range sFlags {
  148. switch flag {
  149. case "":
  150. // Nothing.
  151. case "CHECKLOCKTIMEVERIFY":
  152. flags |= ScriptVerifyCheckLockTimeVerify
  153. case "CHECKSEQUENCEVERIFY":
  154. flags |= ScriptVerifyCheckSequenceVerify
  155. case "CLEANSTACK":
  156. flags |= ScriptVerifyCleanStack
  157. case "DERSIG":
  158. flags |= ScriptVerifyDERSignatures
  159. case "DISCOURAGE_UPGRADABLE_NOPS":
  160. flags |= ScriptDiscourageUpgradableNops
  161. case "LOW_S":
  162. flags |= ScriptVerifyLowS
  163. case "MINIMALDATA":
  164. flags |= ScriptVerifyMinimalData
  165. case "NONE":
  166. // Nothing.
  167. case "NULLDUMMY":
  168. flags |= ScriptStrictMultiSig
  169. case "NULLFAIL":
  170. flags |= ScriptVerifyNullFail
  171. case "P2SH":
  172. flags |= ScriptBip16
  173. case "SIGPUSHONLY":
  174. flags |= ScriptVerifySigPushOnly
  175. case "STRICTENC":
  176. flags |= ScriptVerifyStrictEncoding
  177. case "WITNESS":
  178. flags |= ScriptVerifyWitness
  179. case "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM":
  180. flags |= ScriptVerifyDiscourageUpgradeableWitnessProgram
  181. case "MINIMALIF":
  182. flags |= ScriptVerifyMinimalIf
  183. case "WITNESS_PUBKEYTYPE":
  184. flags |= ScriptVerifyWitnessPubKeyType
  185. default:
  186. return flags, er.Errorf("invalid flag: %s", flag)
  187. }
  188. }
  189. return flags, nil
  190. }
  191. // parseExpectedResult parses the provided expected result string into allowed
  192. // script error codes. An error is returned if the expected result string is
  193. // not supported.
  194. func parseExpectedResult(expected string) ([]*er.ErrorCode, er.R) {
  195. switch expected {
  196. case "OK":
  197. return nil, nil
  198. case "UNKNOWN_ERROR":
  199. return []*er.ErrorCode{txscripterr.ErrNumberTooBig, txscripterr.ErrMinimalData}, nil
  200. case "PUBKEYTYPE":
  201. return []*er.ErrorCode{txscripterr.ErrPubKeyType}, nil
  202. case "SIG_DER":
  203. return []*er.ErrorCode{
  204. txscripterr.ErrSigTooShort, txscripterr.ErrSigTooLong,
  205. txscripterr.ErrSigInvalidSeqID, txscripterr.ErrSigInvalidDataLen, txscripterr.ErrSigMissingSTypeID,
  206. txscripterr.ErrSigMissingSLen, txscripterr.ErrSigInvalidSLen,
  207. txscripterr.ErrSigInvalidRIntID, txscripterr.ErrSigZeroRLen, txscripterr.ErrSigNegativeR,
  208. txscripterr.ErrSigTooMuchRPadding, txscripterr.ErrSigInvalidSIntID,
  209. txscripterr.ErrSigZeroSLen, txscripterr.ErrSigNegativeS, txscripterr.ErrSigTooMuchSPadding,
  210. txscripterr.ErrInvalidSigHashType,
  211. }, nil
  212. case "EVAL_FALSE":
  213. return []*er.ErrorCode{txscripterr.ErrEvalFalse, txscripterr.ErrEmptyStack}, nil
  214. case "EQUALVERIFY":
  215. return []*er.ErrorCode{txscripterr.ErrEqualVerify}, nil
  216. case "NULLFAIL":
  217. return []*er.ErrorCode{txscripterr.ErrNullFail}, nil
  218. case "SIG_HIGH_S":
  219. return []*er.ErrorCode{txscripterr.ErrSigHighS}, nil
  220. case "SIG_HASHTYPE":
  221. return []*er.ErrorCode{txscripterr.ErrInvalidSigHashType}, nil
  222. case "SIG_NULLDUMMY":
  223. return []*er.ErrorCode{txscripterr.ErrSigNullDummy}, nil
  224. case "SIG_PUSHONLY":
  225. return []*er.ErrorCode{txscripterr.ErrNotPushOnly}, nil
  226. case "CLEANSTACK":
  227. return []*er.ErrorCode{txscripterr.ErrCleanStack}, nil
  228. case "BAD_OPCODE":
  229. return []*er.ErrorCode{txscripterr.ErrReservedOpcode, txscripterr.ErrMalformedPush}, nil
  230. case "UNBALANCED_CONDITIONAL":
  231. return []*er.ErrorCode{
  232. txscripterr.ErrUnbalancedConditional,
  233. txscripterr.ErrInvalidStackOperation,
  234. }, nil
  235. case "OP_RETURN":
  236. return []*er.ErrorCode{txscripterr.ErrEarlyReturn}, nil
  237. case "VERIFY":
  238. return []*er.ErrorCode{txscripterr.ErrVerify}, nil
  239. case "INVALID_STACK_OPERATION", "INVALID_ALTSTACK_OPERATION":
  240. return []*er.ErrorCode{txscripterr.ErrInvalidStackOperation}, nil
  241. case "DISABLED_OPCODE":
  242. return []*er.ErrorCode{txscripterr.ErrDisabledOpcode}, nil
  243. case "DISCOURAGE_UPGRADABLE_NOPS":
  244. return []*er.ErrorCode{txscripterr.ErrDiscourageUpgradableNOPs}, nil
  245. case "PUSH_SIZE":
  246. return []*er.ErrorCode{txscripterr.ErrElementTooBig}, nil
  247. case "OP_COUNT":
  248. return []*er.ErrorCode{txscripterr.ErrTooManyOperations}, nil
  249. case "STACK_SIZE":
  250. return []*er.ErrorCode{txscripterr.ErrStackOverflow}, nil
  251. case "SCRIPT_SIZE":
  252. return []*er.ErrorCode{txscripterr.ErrScriptTooBig}, nil
  253. case "PUBKEY_COUNT":
  254. return []*er.ErrorCode{txscripterr.ErrInvalidPubKeyCount}, nil
  255. case "SIG_COUNT":
  256. return []*er.ErrorCode{txscripterr.ErrInvalidSignatureCount}, nil
  257. case "MINIMALDATA":
  258. return []*er.ErrorCode{txscripterr.ErrMinimalData}, nil
  259. case "NEGATIVE_LOCKTIME":
  260. return []*er.ErrorCode{txscripterr.ErrNegativeLockTime}, nil
  261. case "UNSATISFIED_LOCKTIME":
  262. return []*er.ErrorCode{txscripterr.ErrUnsatisfiedLockTime}, nil
  263. case "MINIMALIF":
  264. return []*er.ErrorCode{txscripterr.ErrMinimalIf}, nil
  265. case "DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM":
  266. return []*er.ErrorCode{txscripterr.ErrDiscourageUpgradableWitnessProgram}, nil
  267. case "WITNESS_PROGRAM_WRONG_LENGTH":
  268. return []*er.ErrorCode{txscripterr.ErrWitnessProgramWrongLength}, nil
  269. case "WITNESS_PROGRAM_WITNESS_EMPTY":
  270. return []*er.ErrorCode{txscripterr.ErrWitnessProgramEmpty}, nil
  271. case "WITNESS_PROGRAM_MISMATCH":
  272. return []*er.ErrorCode{txscripterr.ErrWitnessProgramMismatch}, nil
  273. case "WITNESS_MALLEATED":
  274. return []*er.ErrorCode{txscripterr.ErrWitnessMalleated}, nil
  275. case "WITNESS_MALLEATED_P2SH":
  276. return []*er.ErrorCode{txscripterr.ErrWitnessMalleatedP2SH}, nil
  277. case "WITNESS_UNEXPECTED":
  278. return []*er.ErrorCode{txscripterr.ErrWitnessUnexpected}, nil
  279. case "WITNESS_PUBKEYTYPE":
  280. return []*er.ErrorCode{txscripterr.ErrWitnessPubKeyType}, nil
  281. }
  282. return nil, er.Errorf("unrecognized expected result in test data: %v",
  283. expected)
  284. }
  285. // createSpendTx generates a basic spending transaction given the passed
  286. // signature, witness and public key scripts.
  287. func createSpendingTx(witness [][]byte, sigScript, pkScript []byte,
  288. outputValue int64) *wire.MsgTx {
  289. coinbaseTx := wire.NewMsgTx(constants.TxVersion)
  290. outPoint := wire.NewOutPoint(&chainhash.Hash{}, ^uint32(0))
  291. txIn := wire.NewTxIn(outPoint, []byte{opcode.OP_0, opcode.OP_0}, nil)
  292. txOut := wire.NewTxOut(outputValue, pkScript)
  293. coinbaseTx.AddTxIn(txIn)
  294. coinbaseTx.AddTxOut(txOut)
  295. spendingTx := wire.NewMsgTx(constants.TxVersion)
  296. coinbaseTxSha := coinbaseTx.TxHash()
  297. outPoint = wire.NewOutPoint(&coinbaseTxSha, 0)
  298. txIn = wire.NewTxIn(outPoint, sigScript, witness)
  299. txOut = wire.NewTxOut(outputValue, nil)
  300. spendingTx.AddTxIn(txIn)
  301. spendingTx.AddTxOut(txOut)
  302. return spendingTx
  303. }
  304. // scriptWithInputVal wraps a target pkScript with the value of the output in
  305. // which it is contained. The inputVal is necessary in order to properly
  306. // validate inputs which spend nested, or native witness programs.
  307. type scriptWithInputVal struct {
  308. inputVal int64
  309. pkScript []byte
  310. }
  311. // testScripts ensures all of the passed script tests execute with the expected
  312. // results with or without using a signature cache, as specified by the
  313. // parameter.
  314. func testScripts(t *testing.T, tests [][]interface{}, useSigCache bool) {
  315. // Create a signature cache to use only if requested.
  316. var sigCache *SigCache
  317. if useSigCache {
  318. sigCache = NewSigCache(10)
  319. }
  320. for i, test := range tests {
  321. // "Format is: [[wit..., amount]?, scriptSig, scriptPubKey,
  322. // flags, expected_scripterror, ... comments]"
  323. // Skip single line comments.
  324. if len(test) == 1 {
  325. continue
  326. }
  327. // Construct a name for the test based on the comment and test
  328. // data.
  329. name, err := scriptTestName(test)
  330. if err != nil {
  331. t.Errorf("TestScripts: invalid test #%d: %v", i, err)
  332. continue
  333. }
  334. var (
  335. witness wire.TxWitness
  336. inputAmt btcutil.Amount
  337. )
  338. // When the first field of the test data is a slice it contains
  339. // witness data and everything else is offset by 1 as a result.
  340. witnessOffset := 0
  341. if witnessData, ok := test[0].([]interface{}); ok {
  342. witnessOffset++
  343. // If this is a witness test, then the final element
  344. // within the slice is the input amount, so we ignore
  345. // all but the last element in order to parse the
  346. // witness stack.
  347. strWitnesses := witnessData[:len(witnessData)-1]
  348. witness, err = parseWitnessStack(strWitnesses)
  349. if err != nil {
  350. t.Errorf("%s: can't parse witness; %v", name, err)
  351. continue
  352. }
  353. ia, err := globalcfg.NewAmount(witnessData[len(witnessData)-1].(float64))
  354. if err != nil {
  355. t.Errorf("%s: can't parse input amt: %v",
  356. name, err)
  357. continue
  358. }
  359. inputAmt = btcutil.Amount(ia)
  360. }
  361. // Extract and parse the signature script from the test fields.
  362. scriptSigStr, ok := test[witnessOffset].(string)
  363. if !ok {
  364. t.Errorf("%s: signature script is not a string", name)
  365. continue
  366. }
  367. scriptSig, err := parseShortForm(scriptSigStr)
  368. if err != nil {
  369. t.Errorf("%s: can't parse signature script: %v", name,
  370. err)
  371. continue
  372. }
  373. // Extract and parse the public key script from the test fields.
  374. scriptPubKeyStr, ok := test[witnessOffset+1].(string)
  375. if !ok {
  376. t.Errorf("%s: public key script is not a string", name)
  377. continue
  378. }
  379. scriptPubKey, err := parseShortForm(scriptPubKeyStr)
  380. if err != nil {
  381. t.Errorf("%s: can't parse public key script: %v", name,
  382. err)
  383. continue
  384. }
  385. // Extract and parse the script flags from the test fields.
  386. flagsStr, ok := test[witnessOffset+2].(string)
  387. if !ok {
  388. t.Errorf("%s: flags field is not a string", name)
  389. continue
  390. }
  391. flags, err := parseScriptFlags(flagsStr)
  392. if err != nil {
  393. t.Errorf("%s: %v", name, err)
  394. continue
  395. }
  396. // Extract and parse the expected result from the test fields.
  397. //
  398. // Convert the expected result string into the allowed script
  399. // error codes. This is necessary because txscript is more
  400. // fine grained with its errors than the reference test data, so
  401. // some of the reference test data errors map to more than one
  402. // possibility.
  403. resultStr, ok := test[witnessOffset+3].(string)
  404. if !ok {
  405. t.Errorf("%s: result field is not a string", name)
  406. continue
  407. }
  408. allowedErrorCodes, err := parseExpectedResult(resultStr)
  409. if err != nil {
  410. t.Errorf("%s: %v", name, err)
  411. continue
  412. }
  413. // Generate a transaction pair such that one spends from the
  414. // other and the provided signature and public key scripts are
  415. // used, then create a new engine to execute the scripts.
  416. tx := createSpendingTx(witness, scriptSig, scriptPubKey,
  417. int64(inputAmt))
  418. vm, err := NewEngine(scriptPubKey, tx, 0, flags, sigCache, nil,
  419. int64(inputAmt))
  420. if err == nil {
  421. err = vm.Execute()
  422. }
  423. // Ensure there were no errors when the expected result is OK.
  424. if resultStr == "OK" {
  425. if err != nil {
  426. t.Errorf("%s failed to execute: %v", name, err)
  427. }
  428. continue
  429. }
  430. // At this point an error was expected so ensure the result of
  431. // the execution matches it.
  432. success := false
  433. for _, code := range allowedErrorCodes {
  434. if code.Is(err) {
  435. success = true
  436. break
  437. }
  438. }
  439. if !success {
  440. t.Errorf("%s: want error codes %v, got err: %v (%T)",
  441. name, allowedErrorCodes, err, err)
  442. continue
  443. }
  444. }
  445. }
  446. // TestScripts ensures all of the tests in script_tests.json execute with the
  447. // expected results as defined in the test data.
  448. func TestScripts(t *testing.T) {
  449. file, err := ioutil.ReadFile("data/script_tests.json")
  450. if err != nil {
  451. t.Fatalf("TestScripts: %v\n", err)
  452. }
  453. var tests [][]interface{}
  454. err = jsoniter.Unmarshal(file, &tests)
  455. if err != nil {
  456. t.Fatalf("TestScripts couldn't Unmarshal: %v", err)
  457. }
  458. // Run all script tests with and without the signature cache.
  459. testScripts(t, tests, true)
  460. testScripts(t, tests, false)
  461. }
  462. // testVecF64ToUint32 properly handles conversion of float64s read from the JSON
  463. // test data to unsigned 32-bit integers. This is necessary because some of the
  464. // test data uses -1 as a shortcut to mean max uint32 and direct conversion of a
  465. // negative float to an unsigned int is implementation dependent and therefore
  466. // doesn't result in the expected value on all platforms. This function woks
  467. // around that limitation by converting to a 32-bit signed integer first and
  468. // then to a 32-bit unsigned integer which results in the expected behavior on
  469. // all platforms.
  470. func testVecF64ToUint32(f float64) uint32 {
  471. return uint32(int32(f))
  472. }
  473. // TestTxInvalidTests ensures all of the tests in tx_invalid.json fail as
  474. // expected.
  475. func TestTxInvalidTests(t *testing.T) {
  476. file, err := ioutil.ReadFile("data/tx_invalid.json")
  477. if err != nil {
  478. t.Fatalf("TestTxInvalidTests: %v\n", err)
  479. }
  480. var tests [][]interface{}
  481. err = jsoniter.Unmarshal(file, &tests)
  482. if err != nil {
  483. t.Fatalf("TestTxInvalidTests couldn't Unmarshal: %v\n", err)
  484. }
  485. // form is either:
  486. // ["this is a comment "]
  487. // or:
  488. // [[[previous hash, previous index, previous scriptPubKey]...,]
  489. // serializedTransaction, verifyFlags]
  490. testloop:
  491. for i, test := range tests {
  492. inputs, ok := test[0].([]interface{})
  493. if !ok {
  494. continue
  495. }
  496. if len(test) != 3 {
  497. t.Errorf("bad test (bad length) %d: %v", i, test)
  498. continue
  499. }
  500. serializedhex, ok := test[1].(string)
  501. if !ok {
  502. t.Errorf("bad test (arg 2 not string) %d: %v", i, test)
  503. continue
  504. }
  505. serializedTx, errr := hex.DecodeString(serializedhex)
  506. if errr != nil {
  507. t.Errorf("bad test (arg 2 not hex %v) %d: %v", errr, i,
  508. test)
  509. continue
  510. }
  511. tx, err := btcutil.NewTxFromBytes(serializedTx)
  512. if err != nil {
  513. t.Errorf("bad test (arg 2 not msgtx %v) %d: %v", err,
  514. i, test)
  515. continue
  516. }
  517. verifyFlags, ok := test[2].(string)
  518. if !ok {
  519. t.Errorf("bad test (arg 3 not string) %d: %v", i, test)
  520. continue
  521. }
  522. flags, err := parseScriptFlags(verifyFlags)
  523. if err != nil {
  524. t.Errorf("bad test %d: %v", i, err)
  525. continue
  526. }
  527. prevOuts := make(map[wire.OutPoint]scriptWithInputVal)
  528. for j, iinput := range inputs {
  529. input, ok := iinput.([]interface{})
  530. if !ok {
  531. t.Errorf("bad test (%dth input not array)"+
  532. "%d: %v", j, i, test)
  533. continue testloop
  534. }
  535. if len(input) < 3 || len(input) > 4 {
  536. t.Errorf("bad test (%dth input wrong length)"+
  537. "%d: %v", j, i, test)
  538. continue testloop
  539. }
  540. previoustx, ok := input[0].(string)
  541. if !ok {
  542. t.Errorf("bad test (%dth input hash not string)"+
  543. "%d: %v", j, i, test)
  544. continue testloop
  545. }
  546. prevhash, err := chainhash.NewHashFromStr(previoustx)
  547. if err != nil {
  548. t.Errorf("bad test (%dth input hash not hash %v)"+
  549. "%d: %v", j, err, i, test)
  550. continue testloop
  551. }
  552. idxf, ok := input[1].(float64)
  553. if !ok {
  554. t.Errorf("bad test (%dth input idx not number)"+
  555. "%d: %v", j, i, test)
  556. continue testloop
  557. }
  558. idx := testVecF64ToUint32(idxf)
  559. oscript, ok := input[2].(string)
  560. if !ok {
  561. t.Errorf("bad test (%dth input script not "+
  562. "string) %d: %v", j, i, test)
  563. continue testloop
  564. }
  565. script, err := parseShortForm(oscript)
  566. if err != nil {
  567. t.Errorf("bad test (%dth input script doesn't "+
  568. "parse %v) %d: %v", j, err, i, test)
  569. continue testloop
  570. }
  571. var inputValue float64
  572. if len(input) == 4 {
  573. inputValue, ok = input[3].(float64)
  574. if !ok {
  575. t.Errorf("bad test (%dth input value not int) "+
  576. "%d: %v", j, i, test)
  577. continue
  578. }
  579. }
  580. v := scriptWithInputVal{
  581. inputVal: int64(inputValue),
  582. pkScript: script,
  583. }
  584. prevOuts[*wire.NewOutPoint(prevhash, idx)] = v
  585. }
  586. for k, txin := range tx.MsgTx().TxIn {
  587. prevOut, ok := prevOuts[txin.PreviousOutPoint]
  588. if !ok {
  589. t.Errorf("bad test (missing %dth input) %d:%v",
  590. k, i, test)
  591. continue testloop
  592. }
  593. // These are meant to fail, so as soon as the first
  594. // input fails the transaction has failed. (some of the
  595. // test txns have good inputs, too..
  596. vm, err := NewEngine(prevOut.pkScript, tx.MsgTx(), k,
  597. flags, nil, nil, prevOut.inputVal)
  598. if err != nil {
  599. continue testloop
  600. }
  601. err = vm.Execute()
  602. if err != nil {
  603. continue testloop
  604. }
  605. }
  606. t.Errorf("test (%d:%v) succeeded when should fail",
  607. i, test)
  608. }
  609. }
  610. // TestTxValidTests ensures all of the tests in tx_valid.json pass as expected.
  611. func TestTxValidTests(t *testing.T) {
  612. file, err := ioutil.ReadFile("data/tx_valid.json")
  613. if err != nil {
  614. t.Fatalf("TestTxValidTests: %v\n", err)
  615. }
  616. var tests [][]interface{}
  617. err = jsoniter.Unmarshal(file, &tests)
  618. if err != nil {
  619. t.Fatalf("TestTxValidTests couldn't Unmarshal: %v\n", err)
  620. }
  621. // form is either:
  622. // ["this is a comment "]
  623. // or:
  624. // [[[previous hash, previous index, previous scriptPubKey, input value]...,]
  625. // serializedTransaction, verifyFlags]
  626. testloop:
  627. for i, test := range tests {
  628. inputs, ok := test[0].([]interface{})
  629. if !ok {
  630. continue
  631. }
  632. if len(test) != 3 {
  633. t.Errorf("bad test (bad length) %d: %v", i, test)
  634. continue
  635. }
  636. serializedhex, ok := test[1].(string)
  637. if !ok {
  638. t.Errorf("bad test (arg 2 not string) %d: %v", i, test)
  639. continue
  640. }
  641. serializedTx, errr := hex.DecodeString(serializedhex)
  642. if errr != nil {
  643. t.Errorf("bad test (arg 2 not hex %v) %d: %v", errr, i,
  644. test)
  645. continue
  646. }
  647. tx, err := btcutil.NewTxFromBytes(serializedTx)
  648. if err != nil {
  649. t.Errorf("bad test (arg 2 not msgtx %v) %d: %v", err,
  650. i, test)
  651. continue
  652. }
  653. verifyFlags, ok := test[2].(string)
  654. if !ok {
  655. t.Errorf("bad test (arg 3 not string) %d: %v", i, test)
  656. continue
  657. }
  658. flags, err := parseScriptFlags(verifyFlags)
  659. if err != nil {
  660. t.Errorf("bad test %d: %v", i, err)
  661. continue
  662. }
  663. prevOuts := make(map[wire.OutPoint]scriptWithInputVal)
  664. for j, iinput := range inputs {
  665. input, ok := iinput.([]interface{})
  666. if !ok {
  667. t.Errorf("bad test (%dth input not array)"+
  668. "%d: %v", j, i, test)
  669. continue
  670. }
  671. if len(input) < 3 || len(input) > 4 {
  672. t.Errorf("bad test (%dth input wrong length)"+
  673. "%d: %v", j, i, test)
  674. continue
  675. }
  676. previoustx, ok := input[0].(string)
  677. if !ok {
  678. t.Errorf("bad test (%dth input hash not string)"+
  679. "%d: %v", j, i, test)
  680. continue
  681. }
  682. prevhash, err := chainhash.NewHashFromStr(previoustx)
  683. if err != nil {
  684. t.Errorf("bad test (%dth input hash not hash %v)"+
  685. "%d: %v", j, err, i, test)
  686. continue
  687. }
  688. idxf, ok := input[1].(float64)
  689. if !ok {
  690. t.Errorf("bad test (%dth input idx not number)"+
  691. "%d: %v", j, i, test)
  692. continue
  693. }
  694. idx := testVecF64ToUint32(idxf)
  695. oscript, ok := input[2].(string)
  696. if !ok {
  697. t.Errorf("bad test (%dth input script not "+
  698. "string) %d: %v", j, i, test)
  699. continue
  700. }
  701. script, err := parseShortForm(oscript)
  702. if err != nil {
  703. t.Errorf("bad test (%dth input script doesn't "+
  704. "parse %v) %d: %v", j, err, i, test)
  705. continue
  706. }
  707. var inputValue float64
  708. if len(input) == 4 {
  709. inputValue, ok = input[3].(float64)
  710. if !ok {
  711. t.Errorf("bad test (%dth input value not int) "+
  712. "%d: %v", j, i, test)
  713. continue
  714. }
  715. }
  716. v := scriptWithInputVal{
  717. inputVal: int64(inputValue),
  718. pkScript: script,
  719. }
  720. prevOuts[*wire.NewOutPoint(prevhash, idx)] = v
  721. }
  722. for k, txin := range tx.MsgTx().TxIn {
  723. prevOut, ok := prevOuts[txin.PreviousOutPoint]
  724. if !ok {
  725. t.Errorf("bad test (missing %dth input) %d:%v",
  726. k, i, test)
  727. continue testloop
  728. }
  729. vm, err := NewEngine(prevOut.pkScript, tx.MsgTx(), k,
  730. flags, nil, nil, prevOut.inputVal)
  731. if err != nil {
  732. t.Errorf("test (%d:%v:%d) failed to create "+
  733. "script: %v", i, test, k, err)
  734. continue
  735. }
  736. err = vm.Execute()
  737. if err != nil {
  738. t.Errorf("test (%d:%v:%d) failed to execute: "+
  739. "%v", i, test, k, err)
  740. continue
  741. }
  742. }
  743. }
  744. }
  745. // TestCalcSignatureHash runs the Bitcoin Core signature hash calculation tests
  746. // in sighash.json.
  747. // https://github.com/bitcoin/bitcoin/blob/master/src/test/data/sighash.json
  748. func TestCalcSignatureHash(t *testing.T) {
  749. file, err := ioutil.ReadFile("data/sighash.json")
  750. if err != nil {
  751. t.Fatalf("TestCalcSignatureHash: %v\n", err)
  752. }
  753. var tests [][]interface{}
  754. err = jsoniter.Unmarshal(file, &tests)
  755. if err != nil {
  756. t.Fatalf("TestCalcSignatureHash couldn't Unmarshal: %v\n",
  757. err)
  758. }
  759. for i, test := range tests {
  760. if i == 0 {
  761. // Skip first line -- contains comments only.
  762. continue
  763. }
  764. if len(test) != 5 {
  765. t.Fatalf("TestCalcSignatureHash: Test #%d has "+
  766. "wrong length.", i)
  767. }
  768. var tx wire.MsgTx
  769. rawTx, _ := hex.DecodeString(test[0].(string))
  770. err := tx.Deserialize(bytes.NewReader(rawTx))
  771. if err != nil {
  772. t.Errorf("TestCalcSignatureHash failed test #%d: "+
  773. "Failed to parse transaction: %v", i, err)
  774. continue
  775. }
  776. subScript, _ := hex.DecodeString(test[1].(string))
  777. parsedScript, err := parsescript.ParseScript(subScript)
  778. if err != nil {
  779. t.Errorf("TestCalcSignatureHash failed test #%d: "+
  780. "Failed to parse sub-script: %v", i, err)
  781. continue
  782. }
  783. hashType := params.SigHashType(testVecF64ToUint32(test[3].(float64)))
  784. hash := calcSignatureHash(parsedScript, hashType, &tx,
  785. int(test[2].(float64)))
  786. expectedHash, _ := chainhash.NewHashFromStr(test[4].(string))
  787. if !bytes.Equal(hash, expectedHash[:]) {
  788. t.Errorf("TestCalcSignatureHash failed test #%d: "+
  789. "Signature hash mismatch.", i)
  790. }
  791. }
  792. }