THORChain memoless swaps

Memoless swaps permit coins with long addresses and/or restricted memo space,
such as Monero, for example, to be swapped on THORChain.  They introduce added
complexity, along with certain privacy and security tradeoffs, so should only
be used for assets that cannot be swapped the usual way.

A reference request transaction (a.k.a. registration transaction) containing
the memo is sent to the THORChain network, which assigns it a number.  This
number is then encoded in the send amount of the swap transaction in lieu of
a memo.

See https://dev.thorchain.org/swap-guide/memoless-swaps.html for technical
details.

While this patch fully implements the feature in MMGen Wallet, it’s disabled
on mainnet for the time being.  Mainnet will be enabled after memoless swaps
are unhalted on THORChain mainnet and the feature can undergo live testing.

The following example is provided for purposes of illustration only. Normally
we would swap LTC to BCH the standard way.

Sample LTC-to-BCH memoless swap workflow (assumes --autosign):

    # Create the reference request transaction (pass 1):
    $ mmgen-swaptxcreate --memoless LTC 1.2345 BCH

    # Autosign the reference request transaction and send it:
    $ mmgen-txsend
    => TxID

    # Get the reference number from the THORChain network:
    $ mmgen-remote --coin=rune get_refnum TxID
    => REFNUM

    # Create the swap transaction (pass 2):
    $ mmgen-swaptxcreate --refnum=REFNUM LTC 1.2345 BCH

    # Sign and send the swap transaction:
    $ mmgen-txsend

    # Monitor your BCH wallet for the funds:
    $ mmgen-tool --coin=bch twview

Testing/demo:

    $ test/cmdtest.py -e swap.memoless

Note that the real send amount is the amount specified in the second invocation
of ‘mmgen-swaptxcreate’ (i.e. the swap transaction or second pass).  If you
omit the --trade-limit option, the amounts in the two invocations can differ,
otherwise amount and trade limit must be identical for both invocations.

Before sending, the software checks that the provided reference number is valid
and points to an address in the user’s tracking wallet.  Thus funds cannot be
sent to the wrong destination as a result of user error.

References remain valid for approximately six hours.  Before sending, the
software checks that the reference is valid, but not whether it is close to
expiration.  If the reference later expires before the swap transaction is
confirmed, there’s a danger of funds loss.  Therefore, it’s recommended to
create and broadcast the swap transaction without delay.  If necessary, the
transaction can be bumped to ensure timely confirmation.

In order to create and send the reference request transaction, the user must
have some RUNE in their wallet.  The current cost per transaction is 0.2 RUNE.

Also be aware of the privacy implications.  Swaps can easily be correlated if
their registration transactions spend from the same RUNE address, or from RUNE
addresses that can be linked via chain analysis.

More complete documentation will be provided at a later date.
This commit is contained in:
The MMGen Project 2026-10-12 10:04:48 +00:00
commit ffe488ffbd
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
33 changed files with 839 additions and 45 deletions

View file

@ -220,7 +220,7 @@ class ETHAmt(CoinAmt):
szabo = Decimal('0.000001')
finney = Decimal('0.001')
atomic = wei
units = ('wei', 'Kwei', 'Mwei', 'Gwei', 'szabo', 'finney')
units = ('atomic', 'wei', 'Kwei', 'Mwei', 'Gwei', 'szabo', 'finney')
def toWei(self):
return int(Decimal(self) // self.wei)

View file

@ -1 +1 @@
16.3.0dev15
16.3.0dev16

View file

@ -131,6 +131,9 @@ mods = {
'wif2redeem_script',
'wif2segwit_pair',
),
'amt': (
'memoless_amt',
),
'mnemonic': (
'hex2mn',
'mn2hex',

View file

@ -30,7 +30,10 @@ opts_data = {
'tx': ['-', 't'],
'swaptx': ['-', 's'],
}[target],
'sets': [('yes', True, 'quiet', True)],
'sets': [
('yes', True, 'quiet', True),
('refnum', bool, 'memoless', True),
('no_refreq_tx', True, 'memoless', True)],
'requires': [('coin', 'XMR', 'autosign', True)],
'text': {
'desc': {
@ -73,6 +76,12 @@ opts_data = {
b- -L, --autochg-ignore-labels Ignore labels when autoselecting change addresses
-- -m, --minconf= n Minimum number of confirmations required to spend
+ outputs (default: 1)
-s -M, --memoless Perform a memoless swap, creating a reference request
+ TX (activates first pass).
-s -n, --refnum=N The memoless reference number obtained after sending
+ the reference request TX (activates second pass).
-s -N, --no-refreq-tx With --memoless, do not create a reference request TX.
+ Instead, display the reference memo and exit.
m- -p, --priority=N Specify an integer priority ‘N’ for inclusion of trans-
+ action in blockchain (higher number means higher fee).
+ Valid parameters: {tp}.
@ -155,7 +164,7 @@ async def main():
from .tx import NewTX
if target == 'swaptx':
from .tx.new_swap import get_send_proto
tx1 = NewTX(cfg=cfg, proto=get_send_proto(cfg), target=target)
tx1 = NewTX(cfg=cfg, proto=get_send_proto(cfg), target=target, is_memoless=cfg.memoless)
else:
tx1 = NewTX(cfg=cfg, proto=cfg._proto, target=target)
@ -164,7 +173,18 @@ async def main():
locktime = int(cfg.locktime or 0),
do_info = cfg.info)
if not tx1.is_compat:
if tx1.is_compat:
return
if tx1.is_swap and tx1.is_refreq: # memoless first pass
if cfg.no_refreq_tx:
Msg(f'MEMO: {tx1.reference_memo}')
else:
rune_cfg = Config({'_clone': cfg, 'coin': 'rune', 'fee': tx1.memoless_tx_fee})
tx2 = NewTX(cfg=rune_cfg, proto=rune_cfg._proto, target='tx', refreq_src=tx1)
tx3 = await tx2.create(args=('deposit,0', f'data:{tx1.reference_memo}'))
write_to_file(tx3, asi)
else:
write_to_file(tx2, asi)
async_run(cfg, main)

View file

@ -175,8 +175,12 @@ async def process_tx(tx):
await tx.post_send(asi)
return 0
if tx.is_swap:
if tx.is_swap or tx.is_refreq:
tx.check_swap_network()
if tx.is_swap:
if tx.is_memoless:
await tx.check_memoless_presend()
if not tx.check_swap_expiry():
die(1, 'Swap quote has expired. Please re-create the transaction')

View file

@ -12,7 +12,7 @@ proto.btc.tx.info: Bitcoin transaction info class
from ....tx.info import TxInfo
from ....util import fmt, die
from ....color import red, green, blue, pink
from ....color import red, green, blue, pink, orange
from ....addr import MMGenID
class TxInfo(TxInfo):
@ -62,10 +62,15 @@ class TxInfo(TxInfo):
append_chars = ('', ' (chg)')[bool(is_output and e.is_chg and terse)],
append_color = 'green')
else:
return MMGenID.fmtc(
'[vault address]' if not is_input and e.is_vault else nonmm_str,
max_mmwid,
color = True)
return (
(orange('[vault refnum ')
+ red(str(tx.refnum))
+ orange(']')
+ (' ' * (max_mmwid - 15 - len(str(tx.refnum))))
if tx.is_memoless and terse and tx.refnum else
MMGenID.fmtc('[vault address]', max_mmwid, color=True))
if is_output and e.is_vault else
MMGenID.fmtc(nonmm_str, max_mmwid, color=True))
def format_io(desc):
io = getattr(tx, desc)
@ -121,6 +126,8 @@ class TxInfo(TxInfo):
if have_bch and e.addr:
yield ('', '', f'[{e.addr.hl(vp2, color=False)}]')
yield from gen_common(e)
if e.is_vault and tx.is_memoless and tx.refnum:
yield ('', 'refnum:', red(str(tx.refnum)))
if e.is_chg:
yield ('', 'change:', green('True'))

View file

@ -65,7 +65,10 @@ class THORChainRemoteRPCClient(RemoteRPCClient):
'acct_info',
'balance',
'quote',
'tx_info')}
'tx_info',
'get_refnum',
'validate_refnum',
'validate_amt')}
def __init__(self, cfg, proto):
for k, v in proto.rpc_remote_params.items():
@ -160,6 +163,34 @@ class THORChainRemoteRPCClient(RemoteRPCClient):
self.swap_api.get(path=f'/thorchain/quote/swap?{qs}'),
errmsg = 'swap quote request failed')
def get_refnum(self, txid: str):
"get reference memo info for a reference request transaction by TxID"
return process_response(
self.rest_api.get(path=f'/thorchain/memo/{txid}'),
errmsg = f'get reference memo info for txid ‘{txid}’ failed')
def validate_refnum(self, asset: str, refnum: str):
"check that given asset/reference combination is valid"
from ....swap.util import get_swap_asset
swap_asset = get_swap_asset(self.cfg, asset, sanitize_input=True)
return process_response(
self.rest_api.get(path=f'/thorchain/memo/{swap_asset.full_name}/{refnum}'),
errmsg = f'asset/reference combination {swap_asset.full_name}/{refnum} is invalid')
def validate_amt(self, asset: str, amt: Decimal):
"check that given asset/amount combination resolves to a valid reference"
from ....swap.util import get_swap_asset, init_swap_proto
swap_asset = get_swap_asset(self.cfg, asset, sanitize_input=True)
return self.do_validate_amt(
swap_asset,
init_swap_proto(self.cfg, swap_asset).coin_amt(amt))
def do_validate_amt(self, asset, amt):
int_amt = amt.to_unit('atomic')
return process_response(
self.rest_api.get(path=f'/thorchain/memo/check/{asset.full_name}/{int_amt}'),
errmsg = f'asset/amount combination {asset.full_name}/{int_amt} is invalid')
def tx_info(self, txid: str):
"get information for a transaction by TxID"
return process_response(

View file

@ -37,7 +37,7 @@ class Base(TxBase):
o = self.txobj
b = tx.body.messages[0].body
if self.is_swap:
if self.is_swap or self.is_deposit:
from_k, amt_k = ('signer', 'coins')
if b.memo != self.swap_memo:
raise ValueError(f'{b.memo}: invalid swap memo in serialized data')

View file

@ -21,7 +21,7 @@ class TxInfo(VmTxInfo, TxInfo):
def format_body(self, blockcount, nonmm_str, max_mmwid, enl, *, terse, sort):
tx = self.tx
t = tx.txobj
has_memo = tx.is_swap
has_memo = tx.is_swap or tx.is_deposit
fs = """
From: {f}{f_mmid}
Amount: {a} {c}

View file

@ -18,9 +18,14 @@ from .base import Base
class New(VmNew, Base, TxBase.New):
def __init__(self, *args, **kwargs):
def __init__(self, *args, refreq_src=None, **kwargs):
super().__init__(*args, **kwargs)
self.usr_fee = None if self.cfg.fee is None else self.proto.coin_amt(self.cfg.fee)
if refreq_src:
d = refreq_src.__dict__
self.__dict__ |= {k: d[k] for k in self.swap_attrs if k in d and k != 'swap_recv_addr_mmid'}
self.is_refreq = True
self.swap_send_asset_spec = refreq_src.send_asset.name
async def get_funds_remaining(self, fee, outputs_sum, start_fee_desc):
res = await self.twctl.get_balance(self.inputs[0].addr)

View file

@ -25,11 +25,13 @@ class Signed(Completed, TxBase.Signed):
b = tx.body.messages[0].body
i = tx.authInfo
from_k, amt_k = ('signer', 'coins') if self.is_swap else ('fromAddress', 'amount')
msg_dep = self.is_swap or self.is_deposit
from_k, amt_k = ('signer', 'coins') if msg_dep else ('fromAddress', 'amount')
self.txobj = {
'from': self.proto.encode_addr_bech32x(getattr(b, from_k)),
'to': None if self.is_swap else self.proto.encode_addr_bech32x(b.toAddress),
'to': None if msg_dep else self.proto.encode_addr_bech32x(b.toAddress),
'amt': self.proto.coin_amt(int(getattr(b, amt_k)[0].amount), from_unit='satoshi'),
'fee': parse_fee(self.proto, tx),
'gas': NonNegativeInt(i.fee.gasLimit),

View file

@ -45,6 +45,9 @@ class Unsigned(VmUnsigned, Completed, TxBase.Unsigned):
if self.is_swap:
from .protobuf import swap_tx_parms as tx_parms
add_parms = {'memo': self.swap_memo}
elif self.is_deposit:
from .protobuf import swap_tx_parms as tx_parms
add_parms = {'memo': self.swap_memo, 'trade': False, 'synth': False}
else:
from .protobuf import send_tx_parms as tx_parms
add_parms = {'to_addr': o['to']}

View file

@ -53,6 +53,9 @@ class New:
return
case 2 if self.is_swap:
process_data_arg(cmd_args[1])
case 2 if cmd_args[0].startswith('deposit,'):
process_data_arg(cmd_args[1])
self.is_deposit = True
case n:
die(1, f'{n} output{suf(n)} specified, but VM transactions must have exactly one')

View file

@ -25,6 +25,14 @@ def quote_client(tx, amt):
from .quote import ThornodeQuote
return ThornodeQuote(tx, amt)
def reference_memo(send_asset, memo):
from .memoless import THORChainReferenceMemo
return THORChainReferenceMemo(send_asset, memo)
def memoless_amt(amt, refnum=None, *, round_down=False):
from .memoless import THORChainMemolessAmount
return THORChainMemolessAmount(amt, refnum=refnum, round_down=round_down)
from .cfg import THORChainSwapCfg as SwapCfg
from .asset import THORChainSwapAsset as SwapAsset

View file

@ -39,6 +39,21 @@ class THORChainMemo:
pat = r'^(' + '|'.join('|'.join(pats) for pats in ops.values()) + r'):\S\S+'
return bool(re.search(pat.encode(), bytes_data))
@classmethod
def digest(cls, parsed_memo):
"""
Produce a human-readable digest from a parsed memo
"""
m = parsed_memo
return '{} {} {} {} {}/{}/{}'.format(
m.proto,
m.function,
m.asset.full_name,
m.address,
m.trade_limit,
m.stream_interval,
m.stream_quantity)
@classmethod
def parse(cls, s):
"""

View file

@ -0,0 +1,53 @@
# MMGen Wallet, a terminal-based cryptocurrency wallet
# Copyright (C)2013-2026 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
"""
swap.proto.thorchain.memoless: THORChain swap protocol memoless classes for the MMGen Wallet suite
"""
from ....amt import CoinAmt, TokenAmt
class THORChainReferenceMemo:
pfx = 'REFERENCE'
def __init__(self, send_asset, memo):
self.send_asset = send_asset
self.memo = memo
def __str__(self):
return f'{self.pfx}:{self.send_asset.full_name}:{self.memo}'
def parse(self, s):
from .asset import THORChainSwapAsset
_, name, self.memo = s.split(':', 2)
self.asset = THORChainSwapAsset(name, 'send', sanitize_input=True)
class THORChainMemolessAmount:
mod = 100000
def __init__(self, amt, refnum=None, *, round_down=False):
assert isinstance(amt, CoinAmt), 'amount must be CoinAmt instance'
if refnum:
adj = lambda diff: diff - (
(self.mod if diff > 0 else 0) if round_down else
(0 if abs(diff) <= self.mod // 2 else self.mod if diff > 0 else -self.mod))
from ....util import is_int
assert is_int(refnum) and refnum < self.mod, f'refnum must be an integer < {self.mod}'
orig_amt = amt.to_unit('atomic')
self.int_amt = orig_amt + adj(refnum - orig_amt % self.mod)
self.amt = type(amt)(
self.int_amt,
from_unit = 'atomic',
decimals = amt.max_prec if isinstance(amt, TokenAmt) else None)
self.refnum = refnum
else:
self.int_amt = amt.to_unit('atomic')
self.amt = amt
self.refnum = self.int_amt % self.mod

View file

@ -31,3 +31,13 @@ def get_swap_asset(cfg, asset, *, direction='send', sanitize_input=False):
"given an asset symbol, and optionally direction, return a swap asset instance"
assert isinstance(asset, str), '‘asset’ must be a string'
return get_swap_proto_mod(cfg.swap_proto).SwapAsset(asset, direction, sanitize_input=sanitize_input)
def get_coin_amt(cfg, asset, amt):
"given an asset symbol and amount (as string), return a coin amount instance"
from ..amt import TokenAmt
assert isinstance(asset, str), '‘asset’ must be a string'
assert isinstance(amt, str), '‘amt’ must be a string'
swap_asset = get_swap_asset(cfg, asset, sanitize_input=True)
return (
TokenAmt(amt, decimals=swap_asset.decimals) if swap_asset.tokensym else
init_swap_proto(cfg, swap_asset).coin_amt(amt))

30
mmgen/tool/amt.py Normal file
View file

@ -0,0 +1,30 @@
# MMGen Wallet, a terminal-based cryptocurrency wallet
# Copyright (C)2013-2026 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
"""
tool.amt: coin amount-related commands for the 'mmgen-tool' utility
"""
from decimal import Decimal
from .common import tool_cmd_base
class tool_cmd(tool_cmd_base):
"coin amount utilities"
need_proto = True
def memoless_amt(self, asset: str, amt: Decimal, refnum: int):
"create a memoless swap amount from a given asset, amount and reference number"
assert self.cfg.coin == 'BTC', '--coin arg not supported for this command'
from ..swap.proto.thorchain.memoless import THORChainMemolessAmount
from ..swap.util import get_coin_amt
return str(THORChainMemolessAmount(get_coin_amt(self.cfg, asset, amt), refnum).amt)

View file

@ -79,16 +79,22 @@ class Base(MMGenObject):
chain = None
signed = False
is_swap = False
is_deposit = False
is_refreq = False
is_memoless = False
is_compat = False
has_comment = True
swap_attrs = {
'swap_proto': None,
'swap_quote_expiry': None,
'swap_send_asset_spec': None,
'swap_recv_addr_mmid': None,
'swap_recv_asset_spec': None,
'swap_memo': None,
'token_vault_addr': None, # nosec # B105
'serialized2': None,
'is_memoless': None,
'refnum': None,
'coin_txid2': CoinTxID}
file_format = 'json'
non_mmgen_inputs_msg = f"""

View file

@ -10,10 +10,21 @@
tx.base_swap: base swap transaction mixin class
"""
from ..util import die, cached_property
from ..util import ymsg, die, cached_property
from ..addr import CoinAddr
class BaseSwapMethods:
data_desc = 'swap transaction data'
@property
def data_desc(self):
def gen():
if self.is_memoless:
yield 'memoless'
yield 'swap'
if self.is_refreq:
yield 'reference request'
yield 'transaction data'
return ' '.join(gen())
@property
def vault_idx(self):
@ -35,7 +46,10 @@ class BaseSwapMethods:
@cached_property
def send_asset(self):
spec = self.proto.coin + (f'.{self.proto.tokensym}' if self.proto.tokensym else '')
spec = getattr(
self,
'swap_send_asset_spec',
self.proto.coin + (f'.{self.proto.tokensym}' if self.proto.tokensym else ''))
return self.swap_proto_mod.SwapAsset(spec, 'send')
@cached_property
@ -52,6 +66,14 @@ class BaseSwapMethods:
def check_swap_network(self):
rpc = self.swap_proto_rpc
if self.is_memoless:
if not self.cfg.test_suite:
die(2, 'Memoless swaps are currently disabled for mainnet in MMGen Wallet')
self.mimir_data = rpc.mimir()
fs = f'Memoless swaps are {{}} on the {self.swap_proto_mod.name} network'
if self.mimir_data['HALTMEMOLESS']:
die(2, fs.format('halted'))
data = rpc.inbound_addrs()
for asset in (self.send_asset, self.recv_asset):
if asset.name != 'RUNE':
@ -61,3 +83,22 @@ class BaseSwapMethods:
('halted', f'halted for asset {asset.name}')):
if rpc.data_for_coin(data, asset.coin)[key]:
die(2, f'Trading is {state} on the {self.swap_proto_mod.name} network')
async def parse_network_memo(self, *, data, recv_asset_spec, recv_twmmid, chk_only=False):
from ..swap.util import init_swap_proto
from ..tw.ctl import TwCtl
pm = self.swap_proto_mod.Memo.parse(data['memo'])
if pm.asset.name != recv_asset_spec:
die(2,
f'receive protocol mismatch: {pm.asset.name!r} (registered memo) '
f'!= {recv_asset_spec!r} (cmdline)')
pm_proto = init_swap_proto(self.cfg, pm.asset)
ra = await (await TwCtl(self.cfg, pm_proto, mode='w')).resolve_address(pm.address)
assert ra, f'unable to resolve address from registered memo {pm.address!r}'
if recv_twmmid and recv_twmmid != ra.twmmid:
ymsg(
f'Warning: address from registered memo ({ra.twmmid!r}) '
f'does not match our destination address ({recv_twmmid!r})')
return None if chk_only else (
self._output(pm.asset.coin, self.cfg.network, CoinAddr(pm_proto, pm.address), ra.twmmid),
pm)

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