Skip to content

Commit 4f7ff00

Browse files
morcossipa
authored andcommitted
[qa] Add rpc test for segwit
Amended by Pieter Wuille to use multisig 1-of-1 for P2WSH tests, and BIP9 based switchover logic. Fixes and py3 conversion by Marco Falke.
1 parent 66cca79 commit 4f7ff00

File tree

5 files changed

+222
-7
lines changed

5 files changed

+222
-7
lines changed

contrib/devtools/check-doc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
REGEX_ARG = re.compile(r'(?:map(?:Multi)?Args(?:\.count\(|\[)|Get(?:Bool)?Arg\()\"(\-[^\"]+?)\"')
2222
REGEX_DOC = re.compile(r'HelpMessageOpt\(\"(\-[^\"=]+?)(?:=|\")')
2323
# list unsupported, deprecated and duplicate args as they need no documentation
24-
SET_DOC_OPTIONAL = set(['-rpcssl', '-benchmark', '-h', '-help', '-socks', '-tor', '-debugnet', '-whitelistalwaysrelay'])
24+
SET_DOC_OPTIONAL = set(['-rpcssl', '-benchmark', '-h', '-help', '-socks', '-tor', '-debugnet', '-whitelistalwaysrelay', '-prematurewitness', '-walletprematurewitness', '-promiscuousmempoolflags'])
2525

2626
def main():
2727
used = check_output(CMD_GREP_ARGS, shell=True)

qa/pull-tester/rpc-tests.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@
136136
'invalidtxrequest.py',
137137
'abandonconflict.py',
138138
'p2p-versionbits-warning.py',
139+
'segwit.py',
139140
'importprunedfunds.py',
140141
'signmessages.py',
141142
]

qa/rpc-tests/segwit.py

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2016 The Bitcoin Core developers
3+
# Distributed under the MIT software license, see the accompanying
4+
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5+
6+
#
7+
# Test the SegWit changeover logic
8+
#
9+
10+
from test_framework.test_framework import BitcoinTestFramework
11+
from test_framework.util import *
12+
from test_framework.mininode import sha256, ripemd160
13+
import os
14+
import shutil
15+
16+
NODE_0 = 0
17+
NODE_1 = 1
18+
NODE_2 = 2
19+
WIT_V0 = 0
20+
WIT_V1 = 1
21+
22+
def witness_script(version, pubkey):
23+
if (version == 0):
24+
pubkeyhash = bytes_to_hex_str(ripemd160(sha256(hex_str_to_bytes(pubkey))))
25+
pkscript = "0014" + pubkeyhash
26+
elif (version == 1):
27+
# 1-of-1 multisig
28+
scripthash = bytes_to_hex_str(sha256(hex_str_to_bytes("5121" + pubkey + "51ae")))
29+
pkscript = "0020" + scripthash
30+
else:
31+
assert("Wrong version" == "0 or 1")
32+
return pkscript
33+
34+
def addlength(script):
35+
scriptlen = format(len(script)//2, 'x')
36+
assert(len(scriptlen) == 2)
37+
return scriptlen + script
38+
39+
def create_witnessprogram(version, node, utxo, pubkey, encode_p2sh, amount):
40+
pkscript = witness_script(version, pubkey);
41+
if (encode_p2sh):
42+
p2sh_hash = bytes_to_hex_str(ripemd160(sha256(hex_str_to_bytes(pkscript))))
43+
pkscript = "a914"+p2sh_hash+"87"
44+
inputs = []
45+
outputs = {}
46+
inputs.append({ "txid" : utxo["txid"], "vout" : utxo["vout"]} )
47+
DUMMY_P2SH = "2MySexEGVzZpRgNQ1JdjdP5bRETznm3roQ2" # P2SH of "OP_1 OP_DROP"
48+
outputs[DUMMY_P2SH] = amount
49+
tx_to_witness = node.createrawtransaction(inputs,outputs)
50+
#replace dummy output with our own
51+
tx_to_witness = tx_to_witness[0:110] + addlength(pkscript) + tx_to_witness[-8:]
52+
return tx_to_witness
53+
54+
def send_to_witness(version, node, utxo, pubkey, encode_p2sh, amount, sign=True, insert_redeem_script=""):
55+
tx_to_witness = create_witnessprogram(version, node, utxo, pubkey, encode_p2sh, amount)
56+
if (sign):
57+
signed = node.signrawtransaction(tx_to_witness)
58+
assert("errors" not in signed or len(["errors"]) == 0)
59+
return node.sendrawtransaction(signed["hex"])
60+
else:
61+
if (insert_redeem_script):
62+
tx_to_witness = tx_to_witness[0:82] + addlength(insert_redeem_script) + tx_to_witness[84:]
63+
64+
return node.sendrawtransaction(tx_to_witness)
65+
66+
def getutxo(txid):
67+
utxo = {}
68+
utxo["vout"] = 0
69+
utxo["txid"] = txid
70+
return utxo
71+
72+
class SegWitTest(BitcoinTestFramework):
73+
74+
def setup_chain(self):
75+
print("Initializing test directory "+self.options.tmpdir)
76+
initialize_chain_clean(self.options.tmpdir, 3)
77+
78+
def setup_network(self):
79+
self.nodes = []
80+
self.nodes.append(start_node(0, self.options.tmpdir, ["-logtimemicros", "-debug", "-walletprematurewitness"]))
81+
self.nodes.append(start_node(1, self.options.tmpdir, ["-logtimemicros", "-debug", "-blockversion=4", "-promiscuousmempoolflags=517", "-prematurewitness", "-walletprematurewitness"]))
82+
self.nodes.append(start_node(2, self.options.tmpdir, ["-logtimemicros", "-debug", "-blockversion=536870915", "-promiscuousmempoolflags=517", "-prematurewitness", "-walletprematurewitness"]))
83+
connect_nodes(self.nodes[1], 0)
84+
connect_nodes(self.nodes[2], 1)
85+
connect_nodes(self.nodes[0], 2)
86+
self.is_network_split = False
87+
self.sync_all()
88+
89+
def success_mine(self, node, txid, sign, redeem_script=""):
90+
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
91+
block = node.generate(1)
92+
assert_equal(len(node.getblock(block[0])["tx"]), 2)
93+
sync_blocks(self.nodes)
94+
95+
def skip_mine(self, node, txid, sign, redeem_script=""):
96+
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
97+
block = node.generate(1)
98+
assert_equal(len(node.getblock(block[0])["tx"]), 1)
99+
sync_blocks(self.nodes)
100+
101+
def fail_accept(self, node, txid, sign, redeem_script=""):
102+
try:
103+
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
104+
except JSONRPCException as exp:
105+
assert(exp.error["code"] == -26)
106+
else:
107+
raise AssertionError("Tx should not have been accepted")
108+
109+
def fail_mine(self, node, txid, sign, redeem_script=""):
110+
send_to_witness(1, node, getutxo(txid), self.pubkey[0], False, Decimal("49.998"), sign, redeem_script)
111+
try:
112+
node.generate(1)
113+
except JSONRPCException as exp:
114+
assert(exp.error["code"] == -1)
115+
else:
116+
raise AssertionError("Created valid block when TestBlockValidity should have failed")
117+
sync_blocks(self.nodes)
118+
119+
def run_test(self):
120+
self.nodes[0].generate(160) #block 160
121+
122+
self.pubkey = []
123+
p2sh_ids = [] # p2sh_ids[NODE][VER] is an array of txids that spend to a witness version VER pkscript to an address for NODE embedded in p2sh
124+
wit_ids = [] # wit_ids[NODE][VER] is an array of txids that spend to a witness version VER pkscript to an address for NODE via bare witness
125+
for i in range(3):
126+
newaddress = self.nodes[i].getnewaddress()
127+
self.pubkey.append(self.nodes[i].validateaddress(newaddress)["pubkey"])
128+
multiaddress = self.nodes[i].addmultisigaddress(1, [self.pubkey[-1]])
129+
self.nodes[i].addwitnessaddress(newaddress)
130+
self.nodes[i].addwitnessaddress(multiaddress)
131+
p2sh_ids.append([])
132+
wit_ids.append([])
133+
for v in range(2):
134+
p2sh_ids[i].append([])
135+
wit_ids[i].append([])
136+
137+
for i in range(5):
138+
for n in range(3):
139+
for v in range(2):
140+
wit_ids[n][v].append(send_to_witness(v, self.nodes[0], self.nodes[0].listunspent()[0], self.pubkey[n], False, Decimal("49.999")))
141+
p2sh_ids[n][v].append(send_to_witness(v, self.nodes[0], self.nodes[0].listunspent()[0], self.pubkey[n], True, Decimal("49.999")))
142+
143+
self.nodes[0].generate(1) #block 161
144+
sync_blocks(self.nodes)
145+
146+
# Make sure all nodes recognize the transactions as theirs
147+
assert_equal(self.nodes[0].getbalance(), 60*50 - 60*50 + 20*Decimal("49.999") + 50)
148+
assert_equal(self.nodes[1].getbalance(), 20*Decimal("49.999"))
149+
assert_equal(self.nodes[2].getbalance(), 20*Decimal("49.999"))
150+
151+
self.nodes[0].generate(262) #block 423
152+
sync_blocks(self.nodes)
153+
154+
print("Verify default node can't accept any witness format txs before fork")
155+
# unsigned, no scriptsig
156+
self.fail_accept(self.nodes[0], wit_ids[NODE_0][WIT_V0][0], False)
157+
self.fail_accept(self.nodes[0], wit_ids[NODE_0][WIT_V1][0], False)
158+
self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], False)
159+
self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], False)
160+
# unsigned with redeem script
161+
self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], False, addlength(witness_script(0, self.pubkey[0])))
162+
self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], False, addlength(witness_script(1, self.pubkey[0])))
163+
# signed
164+
self.fail_accept(self.nodes[0], wit_ids[NODE_0][WIT_V0][0], True)
165+
self.fail_accept(self.nodes[0], wit_ids[NODE_0][WIT_V1][0], True)
166+
self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], True)
167+
self.fail_accept(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], True)
168+
169+
print("Verify witness txs are skipped for mining before the fork")
170+
self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][0], True) #block 424
171+
self.skip_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][0], True) #block 425
172+
self.skip_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][0], True) #block 426
173+
self.skip_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][0], True) #block 427
174+
175+
# TODO: An old node would see these txs without witnesses and be able to mine them
176+
177+
print("Verify unsigned bare witness txs in versionbits-setting blocks are valid before the fork")
178+
self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][1], False) #block 428
179+
self.success_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][1], False) #block 429
180+
181+
print("Verify unsigned p2sh witness txs without a redeem script are invalid")
182+
self.fail_accept(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][1], False)
183+
self.fail_accept(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][1], False)
184+
185+
print("Verify unsigned p2sh witness txs with a redeem script in versionbits-settings blocks are valid before the fork")
186+
self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][1], False, addlength(witness_script(0, self.pubkey[2]))) #block 430
187+
self.success_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][1], False, addlength(witness_script(1, self.pubkey[2]))) #block 431
188+
189+
print("Verify previous witness txs skipped for mining can now be mined")
190+
assert_equal(len(self.nodes[2].getrawmempool()), 4)
191+
block = self.nodes[2].generate(1) #block 432 (first block with new rules; 432 = 144 * 3)
192+
sync_blocks(self.nodes)
193+
assert_equal(len(self.nodes[2].getrawmempool()), 0)
194+
assert_equal(len(self.nodes[2].getblock(block[0])["tx"]), 5)
195+
196+
print("Verify witness txs without witness data are invalid after the fork")
197+
self.fail_mine(self.nodes[2], wit_ids[NODE_2][WIT_V0][2], False)
198+
self.fail_mine(self.nodes[2], wit_ids[NODE_2][WIT_V1][2], False)
199+
self.fail_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V0][2], False, addlength(witness_script(0, self.pubkey[2])))
200+
self.fail_mine(self.nodes[2], p2sh_ids[NODE_2][WIT_V1][2], False, addlength(witness_script(1, self.pubkey[2])))
201+
202+
print("Verify default node can now use witness txs")
203+
self.success_mine(self.nodes[0], wit_ids[NODE_0][WIT_V0][0], True) #block 432
204+
self.success_mine(self.nodes[0], wit_ids[NODE_0][WIT_V1][0], True) #block 433
205+
self.success_mine(self.nodes[0], p2sh_ids[NODE_0][WIT_V0][0], True) #block 434
206+
self.success_mine(self.nodes[0], p2sh_ids[NODE_0][WIT_V1][0], True) #block 435
207+
208+
if __name__ == '__main__':
209+
SegWitTest().main()

src/main.cpp

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1145,8 +1145,8 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C
11451145
return state.DoS(0, false, REJECT_NONSTANDARD, "premature-version2-tx");
11461146
}
11471147

1148-
// Don't accept witness transactions before the final threshold passes
1149-
if (!tx.wit.IsNull() && !IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus())) {
1148+
// Reject transactions with witness before segregated witness activates (override with -prematurewitness)
1149+
if (!GetBoolArg("-prematurewitness",false) && !tx.wit.IsNull() && !IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus())) {
11501150
return state.DoS(0, false, REJECT_NONSTANDARD, "no-witness-yet", true);
11511151
}
11521152

@@ -1487,14 +1487,19 @@ bool AcceptToMemoryPoolWorker(CTxMemPool& pool, CValidationState& state, const C
14871487
}
14881488
}
14891489

1490+
unsigned int scriptVerifyFlags = STANDARD_SCRIPT_VERIFY_FLAGS;
1491+
if (!Params().RequireStandard()) {
1492+
scriptVerifyFlags = GetArg("-promiscuousmempoolflags", scriptVerifyFlags);
1493+
}
1494+
14901495
// Check against previous transactions
14911496
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
1492-
if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true)) {
1497+
if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true)) {
14931498
// SCRIPT_VERIFY_CLEANSTACK requires SCRIPT_VERIFY_WITNESS, so we
14941499
// need to turn both off, and compare against just turning off CLEANSTACK
14951500
// to see if the failure is specifically due to witness validation.
1496-
if (CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true) &&
1497-
!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS & ~SCRIPT_VERIFY_CLEANSTACK, true)) {
1501+
if (CheckInputs(tx, state, view, true, scriptVerifyFlags & ~(SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_CLEANSTACK), true) &&
1502+
!CheckInputs(tx, state, view, true, scriptVerifyFlags & ~SCRIPT_VERIFY_CLEANSTACK, true)) {
14981503
// Only the witness is wrong, so the transaction itself may be fine.
14991504
state.SetCorruptionPossible();
15001505
}

src/wallet/rpcwallet.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1072,7 +1072,7 @@ UniValue addwitnessaddress(const UniValue& params, bool fHelp)
10721072

10731073
{
10741074
LOCK(cs_main);
1075-
if (!IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus())) {
1075+
if (!IsWitnessEnabled(chainActive.Tip(), Params().GetConsensus()) && !GetBoolArg("-walletprematurewitness", false)) {
10761076
throw JSONRPCError(RPC_WALLET_ERROR, "Segregated witness not enabled on network");
10771077
}
10781078
}

0 commit comments

Comments
 (0)