Coverage for tests/wallet/test_multisig.py: 98%

291 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 19:49 +0000

1from __future__ import annotations 

2 

3import logging 

4 

5import pytest 

6from monero import ( 

7 MoneroDaemonRpc, MoneroDestination, MoneroMultisigInitResult, MoneroMultisigSignResult, 

8 MoneroOutputQuery, MoneroOutputWallet, MoneroTxConfig, MoneroTxQuery, MoneroTxSet, MoneroTxWallet, 

9 MoneroUtils, MoneroWallet, MoneroWalletConfig 

10) 

11from typing_extensions import override 

12 

13from utils import GenUtils, MiningUtils, TestUtils, TestUtils as Utils, TxWalletUtils, WalletUtils 

14from .base_test_monero_wallet import BaseTestMoneroWallet 

15from .wallet_support import FullWalletSupport, RpcWalletSupport, KeysWalletSupport 

16 

17logger: logging.Logger = logging.getLogger("TestMoneroWalletMultisig") 

18 

19 

20class BaseTestMoneroWalletMultisig(BaseTestMoneroWallet): 

21 """Common wallet multisig tests.""" 

22 

23 MULTISIG_CONFIGS: list[tuple[int, int]] = [ 

24 (2, 2), # n/n 

25 (2, 3), # (n-1)/n 

26 (2, 4), # m/n 

27 ] 

28 """The multisig wallets that `test_multisig` makes, as (threshold, number of participants).""" 

29 

30 _started_mining: bool = False 

31 """`True` while the daemon mines because a multisig test started it.""" 

32 

33 # Can indicate if multisig import is needed for correct balance information 

34 @pytest.mark.skipif(TestUtils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") 

35 def test_is_multisig_needed(self, wallet: MoneroWallet) -> None: 

36 # TODO test with multisig wallet 

37 multisig_import_needed: bool = wallet.is_multisig_import_needed() 

38 assert multisig_import_needed is False, "Expected non-multisig wallet" 

39 

40 # Supports multisig wallets 

41 @pytest.mark.skipif(TestUtils.TEST_RELAYS is False, reason="TEST_RELAYS disabled") 

42 def test_multisig(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: 

43 for m, n in self.MULTISIG_CONFIGS: 

44 self._test_multisig(daemon, wallet, m, n) 

45 

46 #region Multisig 

47 

48 def _test_multisig(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet, m: int, n: int) -> None: 

49 """Make a m/n multisig wallet, fund it from the test wallet and spend its funds. 

50 

51 :param MoneroDaemonRpc daemon: daemon of the test network. 

52 :param MoneroWallet wallet: test wallet, that funds the multisig wallet and gets the funds back. 

53 :param int m: multisig threshold. 

54 :param int n: number of participants. 

55 """ 

56 # create n participants 

57 participants: list[MoneroWallet] = [] 

58 try: 

59 for _ in range(n): 

60 participants.append(self._create_wallet(MoneroWalletConfig())) 

61 

62 # test multisig 

63 self._test_multisig_participants(daemon, wallet, participants, m, n) 

64 finally: 

65 # stop mining at end of test 

66 self._stop_mining() 

67 

68 # save and close participants 

69 for participant in participants: 

70 self._close_wallet(participant, True) 

71 

72 def _test_multisig_participants( 

73 self, daemon: MoneroDaemonRpc, wallet: MoneroWallet, participants: list[MoneroWallet], m: int, n: int 

74 ) -> None: 

75 """Make the participants a m/n multisig wallet, fund it and spend its funds with a send, a sweep of an output and a sweep. 

76 

77 :param MoneroDaemonRpc daemon: daemon of the test network. 

78 :param MoneroWallet wallet: test wallet, that funds the multisig wallet and gets the funds back. 

79 :param list[MoneroWallet] participants: participants of the multisig wallet. 

80 :param int m: multisig threshold. 

81 :param int n: number of participants. 

82 """ 

83 logger.info(f"test_multisig_participants({m}, {n})") 

84 assert len(participants) == n 

85 

86 # init and fund multisig wallets 

87 account_idx: int = 0 

88 self._init_multisig_wallets(daemon, wallet, participants, m, n, account_idx, 3) 

89 participant: MoneroWallet = participants[0] 

90 

91 # create txs to send funds from a subaddress in the multisig wallet 

92 logger.info("Sending") 

93 config: MoneroTxConfig = MoneroTxConfig() 

94 config.address = wallet.get_address(account_idx, 0) 

95 config.amount = TxWalletUtils.MAX_FEE 

96 config.account_index = account_idx 

97 config.subaddress_indices = [0] 

98 txs: list[MoneroTxWallet] = participant.create_txs(config) 

99 assert len(txs) > 0 

100 tx_set: MoneroTxSet | None = txs[0].tx_set 

101 assert tx_set is not None 

102 self._test_multisig_tx_set(tx_set) 

103 

104 # parse multisig tx hex and test 

105 assert tx_set.multisig_tx_hex is not None 

106 TxWalletUtils.test_described_tx_set(participant.describe_multisig_tx_set(tx_set.multisig_tx_hex), Utils.NETWORK_TYPE) 

107 

108 # sign the tx with participants 1 through m - 1 to meet threshold, and submit it to the network 

109 logger.info("Signing") 

110 tx_hashes: list[str] = self._sign_and_submit(participants, m, tx_set.multisig_tx_hex) 

111 assert len(tx_hashes) > 0 

112 

113 # synchronize the multisig participants since spending outputs 

114 logger.info("Synchronizing participants") 

115 self._synchronize_multisig_participants(participants) 

116 

117 # fetch the wallet's multisig txs 

118 self._test_multisig_txs(participant, tx_hashes) 

119 

120 # sweep an output from subaddress [account_idx, 1] 

121 return_address: str = wallet.get_primary_address() 

122 output_query: MoneroOutputQuery = MoneroOutputQuery() 

123 output_query.account_index = account_idx 

124 output_query.subaddress_index = 1 

125 outputs: list[MoneroOutputWallet] = participant.get_outputs(output_query) 

126 assert len(outputs) > 0 

127 assert outputs[0].is_spent is False 

128 assert outputs[0].key_image is not None 

129 sweep_config: MoneroTxConfig = MoneroTxConfig() 

130 sweep_config.address = return_address 

131 sweep_config.key_image = outputs[0].key_image.hex 

132 sweep_config.relay = True 

133 tx_set = participant.sweep_output(sweep_config).tx_set 

134 assert tx_set is not None 

135 self._test_multisig_tx_set(tx_set) 

136 assert len(tx_set.txs) > 0 

137 

138 # parse multisig tx hex and test 

139 assert tx_set.multisig_tx_hex is not None 

140 TxWalletUtils.test_described_tx_set(participant.describe_multisig_tx_set(tx_set.multisig_tx_hex), Utils.NETWORK_TYPE) 

141 

142 # sign the tx with participants 1 through m - 1 to meet threshold, and submit it to the network 

143 logger.info("Signing sweep output") 

144 tx_hashes = self._sign_and_submit(participants, m, tx_set.multisig_tx_hex) 

145 

146 # synchronize the multisig participants since spending outputs 

147 logger.info("Synchronizing participants") 

148 self._synchronize_multisig_participants(participants) 

149 

150 # fetch the wallet's multisig txs 

151 self._test_multisig_txs(participant, tx_hashes) 

152 

153 # sweep remaining balance 

154 logger.info("Sweeping") 

155 sweep_config = MoneroTxConfig() 

156 sweep_config.address = return_address 

157 sweep_config.account_index = account_idx 

158 sweep_config.relay = True 

159 # TODO: test multisig with sweep_each_subaddress which will generate multiple tx sets without synchronizing participants 

160 txs = participant.sweep_unlocked(sweep_config) 

161 assert len(txs) > 0, "No txs created on sweep_unlocked" 

162 tx_set = txs[0].tx_set 

163 assert tx_set is not None 

164 for tx in txs: 

165 assert tx.tx_set is tx_set 

166 assert tx in tx_set.txs 

167 self._test_multisig_tx_set(tx_set) 

168 

169 # parse multisig tx hex and test 

170 TxWalletUtils.test_described_tx_set(participant.describe_tx_set(tx_set), Utils.NETWORK_TYPE) 

171 

172 # sign the tx with participants 1 through m - 1 to meet threshold, and submit it to the network 

173 logger.info("Signing sweep") 

174 assert tx_set.multisig_tx_hex is not None 

175 tx_hashes = self._sign_and_submit(participants, m, tx_set.multisig_tx_hex) 

176 

177 # synchronize the multisig participants since spending outputs 

178 logger.info("Synchronizing participants") 

179 self._synchronize_multisig_participants(participants) 

180 

181 # fetch the wallet's multisig txs 

182 self._test_multisig_txs(participant, tx_hashes) 

183 

184 def _init_multisig_wallets( 

185 self, daemon: MoneroDaemonRpc, wallet: MoneroWallet, participants: list[MoneroWallet], m: int, n: int, 

186 account_idx: int, num_addresses_to_fund: int 

187 ) -> None: 

188 """Make the participants a m/n multisig wallet and fund subaddresses of its account from the test wallet. 

189 

190 The first participant is restored from the multisig seed, and replaced in `participants`. 

191 

192 :param MoneroDaemonRpc daemon: daemon of the test network. 

193 :param MoneroWallet wallet: test wallet, that funds the multisig wallet. 

194 :param list[MoneroWallet] participants: participants of the multisig wallet. 

195 :param int m: multisig threshold. 

196 :param int n: number of participants. 

197 :param int account_idx: account of the multisig wallet to fund. 

198 :param int num_addresses_to_fund: number of subaddresses of the account to fund (0 to fund nothing). 

199 """ 

200 logger.info(f"init_multisig_wallets({m}, {n})") 

201 assert len(participants) == n 

202 

203 # prepare multisig hexes 

204 prepared_multisig_hexes: list[str] = [participant.prepare_multisig() for participant in participants] 

205 

206 # make wallets multisig 

207 made_multisig_hexes: list[str] = [] 

208 for i, participant in enumerate(participants): 

209 

210 # test bad input 

211 with pytest.raises(Exception) as exc_info: 

212 participant.make_multisig(["asd", "dsa"], m, Utils.WALLET_PASSWORD) 

213 if str(exc_info.value) != "Kex message unexpectedly small.": 

214 logger.warning(f"Unexpected error message: {exc_info.value}") 

215 

216 # collect prepared multisig hexes from wallet's peers and make the wallet multisig 

217 peer_multisig_hexes: list[str] = [peer_hex for j, peer_hex in enumerate(prepared_multisig_hexes) if j != i] 

218 made_multisig_hexes.append(participant.make_multisig(peer_multisig_hexes, m, Utils.WALLET_PASSWORD)) 

219 

220 # try to get seed before wallet initialized 

221 with pytest.raises(Exception) as seed_exc_info: 

222 participants[0].get_seed() 

223 assert str(seed_exc_info.value) == "This wallet is multisig, but not yet finalized" 

224 

225 # exchange keys N - M + 1 times 

226 address: str | None = None 

227 assert len(made_multisig_hexes) == n 

228 prev_multisig_hexes: list[str] = made_multisig_hexes 

229 for i in range(n - m + 1): 

230 

231 # exchange multisig keys with each wallet and collect results 

232 exchange_multisig_hexes: list[str] = [] 

233 for j, participant in enumerate(participants): 

234 

235 # test bad input 

236 with pytest.raises(Exception) as exc_info: 

237 participant.exchange_multisig_keys(["asd", "dsa"], Utils.WALLET_PASSWORD) 

238 assert len(str(exc_info.value)) > 0 

239 

240 # import the multisig hexes of the wallet's peers from last round 

241 peer_multisig_hexes = [peer_hex for k, peer_hex in enumerate(prev_multisig_hexes) if k != j] 

242 result: MoneroMultisigInitResult = participant.exchange_multisig_keys(peer_multisig_hexes, Utils.WALLET_PASSWORD) 

243 

244 # test result 

245 assert result.multisig_hex is not None 

246 assert len(result.multisig_hex) > 0 

247 if i == n - m: # result on last round has address 

248 assert result.address is not None 

249 assert len(result.address) > 0 

250 if address is None: 

251 address = result.address 

252 else: 

253 assert address == result.address 

254 else: 

255 assert result.address is None 

256 exchange_multisig_hexes.append(result.multisig_hex) 

257 

258 # use results for next round of exchange 

259 prev_multisig_hexes = exchange_multisig_hexes 

260 

261 # validate final multisig 

262 participant: MoneroWallet = participants[0] 

263 MoneroUtils.validate_address(participant.get_primary_address(), Utils.NETWORK_TYPE) 

264 WalletUtils.test_multisig_info(participant.get_multisig_info(), m, n) 

265 seed: str = participant.get_seed() 

266 assert len(seed) > 0 

267 

268 # restore participant from multisig seed 

269 self._close_wallet(participant) 

270 restore_config: MoneroWalletConfig = MoneroWalletConfig() 

271 restore_config.restore_height = daemon.get_height() 

272 restore_config.seed = seed 

273 restore_config.is_multisig = True 

274 participant = self._create_wallet(restore_config) 

275 participants[0] = participant 

276 MoneroUtils.validate_address(participant.get_primary_address(), Utils.NETWORK_TYPE) 

277 assert address == participant.get_primary_address() 

278 WalletUtils.test_multisig_info(participant.get_multisig_info(), m, n) 

279 assert seed == participant.get_seed() 

280 

281 # test sending a multisig transaction if configured 

282 if num_addresses_to_fund == 0: 

283 return 

284 

285 # create accounts in the first multisig wallet to receive funds 

286 for _ in range(account_idx): 

287 participant.create_account() 

288 

289 # get destinations to subaddresses within the account of the multisig wallet 

290 destinations: list[MoneroDestination] = [] 

291 for i in range(num_addresses_to_fund): 

292 destinations.append(MoneroDestination(participant.get_address(account_idx, i), MoneroUtils.xmr_to_atomic_units(2))) 

293 if i + 1 < num_addresses_to_fund: 

294 participant.create_subaddress(account_idx) 

295 

296 # wait for txs to confirm and for sufficient unlocked balance 

297 Utils.WALLET_TX_TRACKER.wait_for_txs_to_clear_pool(wallet) 

298 Utils.WALLET_TX_TRACKER.wait_for_unlocked_balance(wallet, 0, None, TxWalletUtils.MAX_FEE * 20) 

299 

300 # send funds from the main test wallet to destinations in the first multisig wallet 

301 assert wallet.get_balance() > 0 

302 logger.info("Sending funds from main wallet") 

303 fund_config: MoneroTxConfig = MoneroTxConfig() 

304 fund_config.account_index = 0 

305 fund_config.destinations = destinations 

306 fund_config.relay = True 

307 wallet.create_tx(fund_config) 

308 

309 # start mining 

310 logger.info("Starting mining") 

311 self._start_mining() 

312 

313 # wait for the multisig wallet's funds to unlock 

314 # TODO: replace with MoneroWalletListener.on_output_received() which is called when output unlocked 

315 last_num_confirmations: int | None = None 

316 while True: 

317 

318 # wait a moment 

319 GenUtils.wait_for(Utils.SYNC_PERIOD_IN_MS) 

320 

321 # fetch and test outputs 

322 outputs: list[MoneroOutputWallet] = participant.get_outputs() 

323 if len(outputs) == 0: 

324 logger.info("No outputs reported yet") 

325 continue 

326 

327 # print num confirmations 

328 output_tx = outputs[0].tx 

329 assert output_tx is not None 

330 output_height: int | None = output_tx.get_height() 

331 assert output_height is not None 

332 num_confirmations: int = daemon.get_height() - output_height 

333 if last_num_confirmations != num_confirmations: 

334 logger.info(f"Output has {num_confirmations} confirmations") 

335 last_num_confirmations = num_confirmations 

336 

337 # outputs are not spent 

338 for output in outputs: 

339 assert output.is_spent is False 

340 

341 # break if output is unlocked 

342 if output_tx.is_locked is False: 

343 break 

344 

345 # stop mining 

346 self._stop_mining() 

347 

348 # multisig wallet should have unlocked balance in subaddresses 0-3 

349 for i in range(num_addresses_to_fund): 

350 assert participant.get_unlocked_balance(account_idx, i) > 0 

351 account_query: MoneroOutputQuery = MoneroOutputQuery() 

352 account_query.account_index = account_idx 

353 outputs = participant.get_outputs(account_query) 

354 assert len(outputs) > 0 

355 if len(outputs) < 3: 

356 logger.warning("Not one output per subaddress?") 

357 for output in outputs: 

358 assert output.tx is not None 

359 assert output.tx.is_locked is False 

360 

361 # wallet requires importing multisig to be reliable 

362 assert participant.is_multisig_import_needed() 

363 

364 # attempt creating and relaying transaction without synchronizing with participants 

365 return_address: str = wallet.get_primary_address() # funds will be returned to this address from the multisig wallet 

366 unsynced_config: MoneroTxConfig = MoneroTxConfig() 

367 unsynced_config.account_index = account_idx 

368 unsynced_config.address = return_address 

369 unsynced_config.amount = TxWalletUtils.MAX_FEE * 3 

370 with pytest.raises(Exception) as exc_info: 

371 participant.create_txs(unsynced_config) 

372 assert str(exc_info.value) == "No transaction created" 

373 

374 # synchronize the multisig participants since receiving outputs 

375 logger.info("Synchronizing participants") 

376 self._synchronize_multisig_participants(participants) 

377 

378 # expect error exporting key images 

379 try: 

380 participant.export_key_images(True) 

381 except Exception as e: 

382 assert "key_image generated not matched with cached key image" in str(e), f"Unexpected error: {e}" 

383 

384 # attempt relaying created transactions without co-signing 

385 relay_config: MoneroTxConfig = MoneroTxConfig() 

386 relay_config.address = return_address 

387 relay_config.amount = TxWalletUtils.MAX_FEE 

388 relay_config.account_index = account_idx 

389 relay_config.subaddress_indices = [0] 

390 relay_config.relay = True 

391 with pytest.raises(Exception) as exc_info: 

392 participant.create_tx(relay_config) 

393 assert str(exc_info.value) == "Cannot relay multisig transaction until co-signed" 

394 

395 @staticmethod 

396 def _sign_and_submit(participants: list[MoneroWallet], m: int, multisig_tx_hex: str) -> list[str]: 

397 """Sign the multisig tx hex with participants 1 through m - 1 to meet the threshold, then submit it with the first one. 

398 

399 :param list[MoneroWallet] participants: participants of the multisig wallet. 

400 :param int m: multisig threshold. 

401 :param str multisig_tx_hex: multisig tx hex to sign. 

402 :returns list[str]: hashes of the submitted txs. 

403 """ 

404 for i in range(1, m): 

405 result: MoneroMultisigSignResult = participants[i].sign_multisig_tx_hex(multisig_tx_hex) 

406 assert result.signed_multisig_tx_hex is not None 

407 multisig_tx_hex = result.signed_multisig_tx_hex 

408 

409 # submit the signed multisig tx hex to the network 

410 logger.info("Submitting") 

411 return participants[0].submit_multisig_tx_hex(multisig_tx_hex) 

412 

413 @staticmethod 

414 def _synchronize_multisig_participants(wallets: list[MoneroWallet]) -> None: 

415 """Synchronize the multisig participants: each one imports the multisig hex of its peers. 

416 

417 :param list[MoneroWallet] wallets: participants of the multisig wallet. 

418 """ 

419 # collect multisig hex of all participants to synchronize 

420 multisig_hexes: list[str] = [] 

421 for wallet in wallets: 

422 wallet.sync() 

423 multisig_hexes.append(wallet.export_multisig_hex()) # TODO: does wallet need saved? 

424 

425 # import each wallet's peer multisig hex 

426 for i, wallet in enumerate(wallets): 

427 peer_multisig_hexes: list[str] = [peer_hex for j, peer_hex in enumerate(multisig_hexes) if j != i] 

428 # TODO monero-project: creating multisig tx fails if wallet not explicitly synced before import_multisig_hex: 

429 # https://github.com/monero-project/monero/issues/6850 

430 wallet.sync() 

431 wallet.import_multisig_hex(peer_multisig_hexes) 

432 

433 @staticmethod 

434 def _test_multisig_tx_set(tx_set: MoneroTxSet) -> None: 

435 """Test that a tx set created by a multisig wallet has only the multisig tx hex.""" 

436 assert tx_set.multisig_tx_hex is not None 

437 assert tx_set.signed_tx_hex is None 

438 assert tx_set.unsigned_tx_hex is None 

439 

440 @staticmethod 

441 def _test_multisig_txs(participant: MoneroWallet, tx_hashes: list[str]) -> None: 

442 """Test that the multisig wallet has the submitted txs.""" 

443 tx_query: MoneroTxQuery = MoneroTxQuery() 

444 tx_query.hashes = tx_hashes 

445 assert len(participant.get_txs(tx_query)) == len(tx_hashes) 

446 

447 def _start_mining(self) -> None: 

448 """Start mining, if the daemon is not mining.""" 

449 if not MiningUtils.is_mining(): 

450 MiningUtils.start_mining() 

451 self._started_mining = True 

452 

453 def _stop_mining(self) -> None: 

454 """Stop mining, if the test started it. 

455 

456 Like monero-java's StartMining.stopMining(), it does not ask the daemon when the test did not start mining: a test that fails 

457 before, or that is not supported (the keys-only wallet), may have no daemon (the unit tests of the CI). 

458 """ 

459 if not self._started_mining: 

460 return 

461 self._started_mining = False 

462 if MiningUtils.is_mining(): 

463 MiningUtils.stop_mining() 

464 

465 #endregion 

466 

467 

468@pytest.mark.integration 

469class TestMoneroWalletFullMultisig(FullWalletSupport, BaseTestMoneroWalletMultisig): 

470 """Full wallet multisig integration tests.""" 

471 

472 # Supports multisig sample code 

473 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") 

474 def test_multisig_sample(self) -> None: 

475 self._test_multisig_sample(1, 2) 

476 self._test_multisig_sample(1, 4) 

477 self._test_multisig_sample(2, 2) 

478 self._test_multisig_sample(2, 3) 

479 self._test_multisig_sample(2, 4) 

480 

481 

482@pytest.mark.integration 

483class TestMoneroWalletRpcMultisig(RpcWalletSupport, BaseTestMoneroWalletMultisig): 

484 """Rpc wallet multisig integration tests.""" 

485 

486 # each participant is a wallet open in a monero-wallet-rpc container, and the tests have only DockerWalletRpcManager.MAX_SLOTS of 

487 # them: monero-java starts a process for each one, and makes also 2/3 and 2/4 multisig wallets 

488 MULTISIG_CONFIGS: list[tuple[int, int]] = [(2, 2)] 

489 

490 # Supports multisig sample code 

491 @pytest.mark.skipif(Utils.TEST_NON_RELAYS is False, reason="TEST_NON_RELAYS disabled") 

492 def test_multisig_sample(self) -> None: 

493 self._test_multisig_sample(1, 2) 

494 self._test_multisig_sample(2, 2) 

495 

496 

497@pytest.mark.unit 

498class TestMoneroWalletKeysMultisig(KeysWalletSupport, BaseTestMoneroWalletMultisig): 

499 """Keys-only wallet multisig unit tests.""" 

500 

501 @pytest.mark.not_supported 

502 @override 

503 def test_is_multisig_needed(self, wallet: MoneroWallet) -> None: 

504 return super().test_is_multisig_needed(wallet) 

505 

506 @pytest.mark.not_supported 

507 @override 

508 def test_multisig(self, daemon: MoneroDaemonRpc, wallet: MoneroWallet) -> None: 

509 return super().test_multisig(daemon, wallet)