THORChain DEX integration

Cross-chain native asset swaps directly from MMGen Wallet!

Currently supported coins: BTC, LTC, BCH.  Work on ETH support is underway.

All supported asset pairs have undergone thorough testing on mainnet.

Sample workflow for a BTC->LTC swap (assumes offline autosigning is set up and
the removable device inserted on the online machine):

    $ mmgen-swaptxcreate --autosign BTC LTC

    remove device - insert - wait for signing - remove - insert

    $ mmgen-txsend --autosign

Note that other command-line options and arguments will likely be required. For
further information, see:

    $ mmgen-swaptxcreate --help

Be aware that transactions stuck for a long time in the mempool can potentially
lead to loss of funds, so users should first learn how to create replacement
transactions with ‘mmgen-txbump’ before attempting a swap.  In all cases, it’s
advisable to begin with small amounts.  Double-checking the vault address on a
block explorer such as thorchain.net or runescan.io before sending the
transaction is also recommended.

Testing:

    $ test/modtest.py tx.memo
    $ test/cmdtest.py regtest_legacy.main autosign_automount swap
This commit is contained in:
The MMGen Project 2025-02-24 11:27:49 +00:00
commit 85cec5655d
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
40 changed files with 1510 additions and 72 deletions

View file

@ -22,6 +22,7 @@ amt: MMGen CoinAmt and related classes
from decimal import Decimal
from .objmethods import Hilite, InitErrors
from .obj import get_obj
class CoinAmt(Decimal, Hilite, InitErrors): # abstract class
"""
@ -155,6 +156,9 @@ class CoinAmt(Decimal, Hilite, InitErrors): # abstract class
def __mod__(self, *args, **kwargs):
self.method_not_implemented()
def is_coin_amt(proto, num, from_unit=None, from_decimal=False):
return get_obj(proto.coin_amt, num=num, from_unit=from_unit, from_decimal=from_decimal, silent=True, return_bool=True)
class BTCAmt(CoinAmt):
coin = 'BTC'
max_prec = 8

View file

@ -1 +1 @@
15.1.dev16
15.1.dev17

View file

@ -70,6 +70,7 @@ class ExtensionModuleError(Exception): mmcode = 2
class MoneroMMGenTXFileParseError(Exception): mmcode = 2
class AutosignTXError(Exception): mmcode = 2
class MMGenImportError(Exception): mmcode = 2
class SwapMemoParseError(Exception): mmcode = 2
# 3: yellow hl, 'MMGen Error' + exception + message
class RPCFailure(Exception): mmcode = 3

82
mmgen/help/swaptxcreate.py Executable file
View file

@ -0,0 +1,82 @@
#!/usr/bin/env python3
#
# MMGen Wallet, a terminal-based cryptocurrency wallet
# Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen-wallet
# https://gitlab.com/mmgen/mmgen-wallet
"""
help.swaptxcreate: swaptxcreate and swaptxdo help notes for the MMGen Wallet suite
"""
def help(proto, cfg):
return """
This script is similar in operation to ‘mmgen-txcreate’, only with additional
steps. Users are advised to first familiarize themselves with the use of that
script before attempting to perform a swap with this one.
The tracking wallets of both the send and receive coins must be available when
the script is invoked. If the two coin daemons are running on different hosts
than the script, or with non-standard ports, coin-specific RPC options may be
required (see EXAMPLES below).
The swap protocol’s quote server on the Internet must be reachable either
directly or via the SOCKS5 proxy specified with the --proxy option. To improve
privacy, it’s recommended to proxy requests to the quote server via Tor or
some other anonymity network.
The resulting transaction file is saved, signed, sent, and optionally bumped,
exactly the same way as one created with ‘mmgen-txcreate’. Autosign with
automount is likewise supported via the --autosign option.
The command line must contain at minimum a send coin (COIN1) and receive coin
(COIN2) symbol. Currently supported coins are BTC, LTC and BCH. All other
arguments are optional. If AMT is specified, the specified value of send coin
will be swapped and the rest returned to a change address in the originating
tracking wallet. Otherwise, the entire value of the interactively selected
inputs will be swapped.
By default, the change and destination addresses are chosen automatically by
finding the lowest-indexed unused addresses of the preferred address types in
the send and receive tracking wallets. Types ‘B’, ‘S’ and ‘C’ (see ADDRESS
TYPES below) are searched in that order for unused addresses.
If the wallet contains eligible unused addresses with multiple Seed IDs, the
user will be presented with a list of the lowest-indexed addresses of
preferred type for each Seed ID and prompted to choose from among them.
Change and destination addresses may also be specified manually with the
CHG_ADDR and ADDR arguments. These may be given as full MMGen IDs or in the
form ADDRTYPE_CODE or SEED_ID:ADDRTYPE_CODE (see EXAMPLES below and the
‘mmgen-txcreate’ help screen for details).
While discouraged, sending change or swapping to non-wallet addresses is also
supported, in which case the signing script (‘mmgen-txsign’ or ‘mmgen-
autosign’, as applicable) must be invoked with the --allow-non-wallet-swap
option.
Rather than specifying a transaction fee on the command line, it’s advisable
to start with the fee suggested by the swap protocol quote server (the script
does this automatically) and then adjust the fee interactively if desired.
When choosing a fee, bear in mind that the longer the transaction remains
unconfirmed, the greater the risk that the vault address will expire, leading
to loss of funds. It’s therefore advisable to learn how to create, sign and
send replacement transactions with ‘mmgen-txbump’ before performing a swap
with this script. When bumping a stuck swap transaction, the safest option
is to create a replacement transaction with one output that returns funds back
to the originating tracking wallet, thus aborting the swap, rather than one
that merely increases the fee (see EXAMPLES below).
Before broadcasting the transaction, it’s advisable to double-check the vault
address on a block explorer such as thorchain.net or runescan.io.
The MMGen Node Tools suite contains two useful tools to help with fine-tuning
transaction fees, ‘mmnode-feeview’ and ‘mmnode-blocks-info’, in addition to
‘mmnode-ticker’, which can be used to calculate the current cross-rate between
the asset pair of a swap, as well as the total receive value in terms of the
send value.
"""

View file

@ -0,0 +1,72 @@
#!/usr/bin/env python3
#
# MMGen Wallet, a terminal-based cryptocurrency wallet
# Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
# Licensed under the GNU General Public License, Version 3:
# https://www.gnu.org/licenses
# Public project repositories:
# https://github.com/mmgen/mmgen-wallet
# https://gitlab.com/mmgen/mmgen-wallet
"""
help.swaptxcreate_examples: swaptxcreate and swaptxdo help examples for the MMGen Wallet suite
"""
from ..cfg import gc
def help(proto, cfg):
return f"""
EXAMPLES:
Create a BTC-to-LTC swap transaction, prompting the user for transaction
inputs. The full value of the inputs, minus miner fees, will be swapped
and sent to an unused address in the user’s LTC tracking wallet:
$ {gc.prog_name} BTC LTC
Same as above, but swap 0.123 BTC, minus miner fees, and send the change to
an unused address in the BTC tracking wallet:
$ {gc.prog_name} BTC 0.123 LTC
Same as above, but specify that the change address be a Segwit P2SH (‘S’)
address:
$ {gc.prog_name} BTC 0.123 S LTC
Same as above, but additionally specify that the destination LTC address be
a compressed P2PKH (‘C’) address:
$ {gc.prog_name} BTC 0.123 S LTC C
Same as above, but specify the BTC change address explicitly and the
destination LTC address by Seed ID and address type:
$ {gc.prog_name} BTC 0.123 BEADCAFE:S:6 LTC BEADCAFE:C
Abort the above swap by creating a replacement transaction that returns the
funds to the originating tracking wallet (omit the transaction filename if
using --autosign):
$ mmgen-txbump BEADCAFE:S:6 [raw transaction file]
Swap 0.123 BTC to a non-wallet address (not recommended):
$ {gc.prog_name} BTC 0.123 LTC ltc1qaq8t3pakcftpk095tnqfv5cmmczysls0xx9388
Create an LTC-to-BCH swap transaction, with the Litecoin daemon running on
host ‘orion’ and Bitcoin Cash Node daemon on host ‘gemini’ with non-standard
RPC port 8332. Communicate with the swap quote server via Tor.
$ {gc.prog_name} --ltc-rpc-host=orion --bch-rpc-host=gemini --bch-rpc-port=8332 --proxy=localhost:9050 LTC BCH
After sending, check the status of the above swap’s LTC deposit transaction
(omit the transaction filename if using --autosign):
$ mmgen-txsend --ltc-rpc-host=orion --status [transaction file]
Check whether the funds have arrived in the BCH destination wallet:
$ mmgen-tool --coin=bch --bch-rpc-host=gemini twview minconf=0
"""

View file

@ -57,6 +57,8 @@ opts_data = {
-v, --verbose Produce more verbose output
-w, --wallet-dir=D Specify an alternate wallet dir
(default: {asi.dfl_wallet_dir!r})
-W, --allow-non-wallet-swap Allow signing of swap transactions that send funds
to non-wallet addresses
-x, --xmrwallets=L Range or list of wallets to be used for XMR autosigning
""",
'notes': """

View file

@ -79,6 +79,9 @@ opts_data = {
-- -s, --send Sign and send the transaction (the default if seed
+ data is provided)
-- -v, --verbose Produce more verbose output
-- -W, --allow-non-wallet-swap Allow signing of swap transactions that send funds
+ to non-wallet addresses
-- -x, --proxy=P Fetch the swap quote via SOCKS5 proxy ‘P’ (host:port)
-- -y, --yes Answer 'yes' to prompts, suppress non-essential output
-- -z, --show-hash-presets Show information on available hash presets
""",
@ -95,6 +98,11 @@ identical to that of ‘mmgen-txcreate’.
The user should take care to select a fee sufficient to ensure the original
transaction is replaced in the mempool.
When bumping a swap transaction, the swap protocol’s quote server on the
Internet must be reachable either directly or via the SOCKS5 proxy specified
with the --proxy option. To improve privacy, it’s recommended to proxy
requests to the quote server via Tor or some other anonymity network.
{e}
{s}
Seed source files must have the canonical extensions listed in the 'FileExt'

View file

@ -73,6 +73,7 @@ opts_data = {
+ Choices: {x_all})
-- -v, --verbose Produce more verbose output
b- -V, --vsize-adj= f Adjust transaction's estimated vsize by factor 'f'
-s -x, --proxy=P Fetch the swap quote via SOCKS5 proxy ‘P’ (host:port)
-- -y, --yes Answer 'yes' to prompts, suppress non-essential output
e- -X, --cached-balances Use cached balances
""",
@ -80,7 +81,7 @@ opts_data = {
},
'code': {
'usage': lambda cfg, proto, help_notes, s: s.format(
u_args = help_notes('txcreate_args')),
u_args = help_notes(f'{target}create_args')),
'options': lambda cfg, proto, help_notes, s: s.format(
cfg = cfg,
cu = proto.coin,
@ -92,10 +93,10 @@ opts_data = {
x_all = fmt_list(cfg._autoset_opts['swap_proto'].choices, fmt='no_spc'),
x_dfl = cfg._autoset_opts['swap_proto'].choices[0]),
'notes': lambda cfg, help_mod, help_notes, s: s.format(
c = help_mod('txcreate'),
c = help_mod(f'{target}create'),
F = help_notes('fee'),
n_at = help_notes('address_types'),
x = help_mod('txcreate_examples'))
x = help_mod(f'{target}create_examples'))
}
}

View file

@ -93,6 +93,7 @@ opts_data = {
+ wallet is scanned for subseeds.
-- -v, --verbose Produce more verbose output
b- -V, --vsize-adj= f Adjust transaction's estimated vsize by factor 'f'
-s -x, --proxy=P Fetch the swap quote via SOCKS5 proxy ‘P’ (host:port)
e- -X, --cached-balances Use cached balances
-- -y, --yes Answer 'yes' to prompts, suppress non-essential output
-- -z, --show-hash-presets Show information on available hash presets
@ -114,7 +115,7 @@ column below:
},
'code': {
'usage': lambda cfg, proto, help_notes, s: s.format(
u_args = help_notes('txcreate_args')),
u_args = help_notes(f'{target}create_args')),
'options': lambda cfg, proto, help_notes, s: s.format(
gc = gc,
cfg = cfg,
@ -134,12 +135,12 @@ column below:
x_all = fmt_list(cfg._autoset_opts['swap_proto'].choices, fmt='no_spc'),
x_dfl = cfg._autoset_opts['swap_proto'].choices[0]),
'notes': lambda cfg, help_mod, help_notes, s: s.format(
c = help_mod('txcreate'),
c = help_mod(f'{target}create'),
F = help_notes('fee'),
n_at = help_notes('address_types'),
f = help_notes('fmt_codes'),
s = help_mod('txsign'),
x = help_mod('txcreate_examples'))
x = help_mod(f'{target}create_examples'))
}
}

View file

@ -110,6 +110,9 @@ async def main():
tx.info.view_with_prompt('View transaction details?', pause=False)
sys.exit(retval)
if tx.is_swap:
tx.check_swap_expiry()
if not cfg.yes:
tx.info.view_with_prompt('View transaction details?')
if tx.add_comment(): # edits an existing comment, returns true if changed

View file

@ -67,6 +67,8 @@ opts_data = {
wallet is scanned for subseeds.
-v, --verbose Produce more verbose output
-V, --vsize-adj= f Adjust transaction's estimated vsize by factor 'f'
-W, --allow-non-wallet-swap Allow signing of swap transactions that send funds
to non-wallet addresses
-y, --yes Answer 'yes' to prompts, suppress non-essential output
""",
'notes': """

View file

@ -21,6 +21,7 @@ from .cashaddr import cashaddr_decode_addr, cashaddr_encode_addr, cashaddr_addr_
class mainnet(mainnet):
is_fork_of = 'Bitcoin'
mmtypes = ('L', 'C')
preferred_mmtypes = ('C',)
sighash_type = 'ALL|FORKID'
forks = [
_finfo(478559, '000000000000000000651ef99cb9fcbe0dadde1d424bd9f15ff20136191a5eec', 'BTC', False)

View file

@ -26,6 +26,7 @@ class mainnet(CoinProtocol.Secp256k1): # chainparams.cpp
addr_len = 20
wif_ver_num = {'std': '80'}
mmtypes = ('L', 'C', 'S', 'B')
preferred_mmtypes = ('B', 'S', 'C')
dfl_mmtype = 'L'
coin_amt = 'BTCAmt'
max_tx_fee = 0.003

View file

@ -250,7 +250,10 @@ class Base(TxBase):
# DATA: opcode_byte ('6a') + push_byte + nulldata_bytes
return sum(
{'p2pkh':34, 'p2sh':32, 'bech32':31}[o.addr.addr_fmt] if o.addr else
(11 + len(o.data))
(11 + len(o.data)) if o.data else
# guess value if o.addr is missing (probably a vault address):
34 if self.proto.coin == 'BCH' else
31
for o in self.outputs)
# https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki
@ -295,6 +298,17 @@ class Base(TxBase):
getattr(self.proto.coin_amt, to_unit) /
self.estimate_size()))
@property
def data_output(self):
res = self.data_outputs
if len(res) > 1:
raise ValueError(f'{res}: too many data outputs in transaction (only one allowed)')
return res[0] if len(res) == 1 else None
@property
def data_outputs(self):
return [o for o in self.outputs if o.data]
@property
def nondata_outputs(self):
return [o for o in self.outputs if not o.data]

View file

@ -14,11 +14,11 @@ proto.btc.tx.bump: Bitcoin transaction bump class
from ....tx import bump as TxBase
from ....util import msg
from .new import New
from .new_swap import NewSwap
from .completed import Completed
from .unsigned import AutomountUnsigned
class Bump(Completed, New, TxBase.Bump):
class Bump(Completed, NewSwap, TxBase.Bump):
desc = 'fee-bumped transaction'
def get_orig_rel_fee(self):

View file

@ -14,7 +14,7 @@ proto.btc.tx.completed: Bitcoin completed transaction class
from ....tx import completed as TxBase
from ....obj import HexStr
from ....util import msg, die
from ....util import msg, ymsg, die
from .base import Base, decodeScriptPubKey
class Completed(Base, TxBase.Completed):
@ -43,6 +43,24 @@ class Completed(Base, TxBase.Completed):
assert (200 < len(ti['scriptSig']) < 300), 'malformed scriptSig' # VERY rough check
return True
def check_swap_memo(self):
if o := self.data_output:
from ....swap.proto.thorchain.memo import Memo
if Memo.is_partial_memo(o.data):
from ....protocol import init_proto
p = Memo.parse(o.data)
assert p.function == 'SWAP', f'‘{p.function}’: unsupported function in swap memo ‘{o.data}’'
assert p.chain == p.asset, f'{p.chain} != {p.asset}: chain/asset mismatch in swap memo ‘{o.data}’'
proto = init_proto(self.cfg, p.asset, network=self.cfg.network, need_amt=True)
if self.swap_recv_addr_mmid:
mmid = self.swap_recv_addr_mmid
elif self.cfg.allow_non_wallet_swap:
ymsg('Warning: allowing swap to non-wallet address (--allow-non-wallet-swap)')
mmid = None
else:
raise ValueError('Swap to non-wallet address forbidden (override with --allow-non-wallet-swap)')
return self.Output(proto, addr=p.address, mmid=mmid, amt=proto.coin_amt('0'))
def check_pubkey_scripts(self):
for n, i in enumerate(self.inputs, 1):
ds = decodeScriptPubKey(self.proto, i.scriptPubKey)

View file

@ -65,7 +65,7 @@ class TxInfo(TxInfo):
append_color='green')
else:
return MMGenID.fmtc(
nonmm_str,
'[vault address]' if not is_input and e.is_vault else nonmm_str,
width = max_mmwid,
color = True)

View file

@ -125,14 +125,17 @@ class New(Base, TxNew):
def final_inputs_ok_msg(self, funds_left):
return 'Transaction produces {} {} in change'.format(funds_left.hl(), self.coin)
def check_chg_addr_is_wallet_addr(self, message='Change address is not an MMGen wallet address!'):
def check_chg_addr_is_wallet_addr(self, output=None, message='Change address is not an MMGen wallet address!'):
def do_err():
from ....ui import confirm_or_raise
confirm_or_raise(
cfg = self.cfg,
message = yellow(message),
action = 'Are you sure this is what you want?')
if len(self.nondata_outputs) > 1 and not self.chg_output.mmid:
if output:
if not output.mmid:
do_err()
elif len(self.nondata_outputs) > 1 and not self.chg_output.mmid:
do_err()
async def create_serialized(self, locktime=None):

View file

@ -12,12 +12,135 @@
proto.btc.tx.new_swap: Bitcoin new swap transaction class
"""
from collections import namedtuple
from ....cfg import gc
from ....tx.new_swap import NewSwap as TxNewSwap
from .new import New
class NewSwap(New, TxNewSwap):
desc = 'Bitcoin swap transaction'
async def process_swap_cmdline_args(self, cmd_args, addrfile_args):
import sys
sys.exit(0)
async def get_swap_output(self, proto, arg, addrfiles, desc):
ret = namedtuple('swap_output', ['coin', 'network', 'addr', 'mmid'])
if arg:
from ..addrdata import TwAddrData
pa = self.parse_cmdline_arg(
proto,
arg,
self.get_addrdata_from_files(proto, addrfiles),
await TwAddrData(self.cfg, proto, twctl=None)) # TODO: twctl required for Ethereum
if pa.addr:
await self.warn_addr_used(proto, pa, desc)
return ret(proto.coin, proto.network, pa.addr, pa.mmid)
full_desc = '{} on the {} {} network'.format(desc, proto.coin, proto.network)
res = await self.get_autochg_addr(proto, arg, exclude=[], desc=full_desc, all_addrtypes=not arg)
self.confirm_autoselected_addr(res.twmmid, full_desc)
return ret(proto.coin, proto.network, res.addr, res.twmmid)
async def process_swap_cmdline_args(self, cmd_args, addrfiles):
from ....protocol import init_proto
import importlib
sp = importlib.import_module(f'mmgen.swap.proto.{self.swap_proto}')
class CmdlineArgs: # listed in command-line order
# send_coin # required: uppercase coin symbol
send_amt = None # optional: Omit to skip change addr and send value of all inputs minus fees to vault
chg_spec = None # optional: change address spec, e.g. ‘B’ ‘DEADBEEF:B’ ‘DEADBEEF:B:1’ or coin address.
# Omit for autoselected change address. Use of non-wallet change address
# will emit warning and prompt user for confirmation
# recv_coin # required: uppercase coin symbol
recv_spec = None # optional: destination address spec. Same rules as for chg_spec
def check_coin_arg(coin, desc):
if coin not in sp.params.coins[desc]:
raise ValueError(f'{coin!r}: unsupported {desc} coin for {gc.proj_name} {sp.name} swap')
return coin
def get_arg():
try:
return args_in.pop(0)
except:
self.cfg._usage()
def init_proto_from_coin(coinsym, desc):
return init_proto(
self.cfg,
check_coin_arg(coinsym, desc),
network = self.proto.network,
need_amt = True)
def parse():
from ....amt import is_coin_amt
arg = get_arg()
# arg 1: send_coin
self.send_proto = init_proto_from_coin(arg, 'send')
arg = get_arg()
# arg 2: amt
if is_coin_amt(self.send_proto, arg):
args.send_amt = self.send_proto.coin_amt(arg)
arg = get_arg()
# arg 3: chg_spec (change address spec)
if args.send_amt:
if not arg in sp.params.coins['receive']: # is change arg
args.chg_spec = arg
arg = get_arg()
# arg 4: recv_coin
self.recv_proto = init_proto_from_coin(arg, 'receive')
# arg 5: recv_spec (receive address spec)
if args_in:
args.recv_spec = get_arg()
if args_in: # done parsing, all args consumed
self.cfg._usage()
args_in = list(cmd_args)
args = CmdlineArgs()
parse()
chg_output = (
await self.get_swap_output(self.send_proto, args.chg_spec, addrfiles, 'change address')
if args.send_amt else None)
if chg_output:
self.check_chg_addr_is_wallet_addr(chg_output)
recv_output = await self.get_swap_output(self.recv_proto, args.recv_spec, addrfiles, 'destination address')
self.check_chg_addr_is_wallet_addr(
recv_output,
message = (
'Swap destination address is not an MMGen wallet address!\n'
'To sign this transaction, autosign or txsign must be invoked with --allow-non-wallet-swap'))
memo = sp.data(self.recv_proto, recv_output.addr)
# this goes into the transaction file:
self.swap_recv_addr_mmid = recv_output.mmid
return (
[f'vault,{args.send_amt}', chg_output.mmid, f'data:{memo}'] if args.send_amt else
['vault', f'data:{memo}'])
def update_vault_addr(self, addr):
vault_idx = self.vault_idx
assert vault_idx == 0, f'{vault_idx}: vault index is not zero!'
o = self.outputs[vault_idx]._asdict()
o['addr'] = addr
self.outputs[vault_idx] = self.Output(self.proto, **o)
@property
def vault_idx(self):
return self._chg_output_ops('idx', 'is_vault')
@property
def vault_output(self):
return self._chg_output_ops('output', 'is_vault')

View file

@ -21,6 +21,7 @@ class mainnet(CoinProtocol.DummyWIF, CoinProtocol.Secp256k1):
network_names = _nw('mainnet', 'testnet', 'devnet')
addr_len = 20
mmtypes = ('E',)
preferred_mmtypes = ('E',)
dfl_mmtype = 'E'
mod_clsname = 'Ethereum'
pubkey_type = 'std' # required by DummyWIF

Some files were not shown because too many files have changed in this diff Show more