P2P integration
Developers12.5.9+

P2P integration

For software that speaks Lotus P2P: protocol version, user agents, the messages a node sends after the handshake, the address query with proofs, light clients after Napoleon.

This page is for wallets, light clients, crawlers and miners that connect to Lotus nodes directly over P2P. The protocol is Bitcoin's, as in Bitcoin ABC, with Lotus messages added. Each Lotus message is optional: a node that does not know a message ignores it and stays connected, and so must your client.

Basics #

Protocol version70016
Portsmainnet 10605, testnet 11605, regtest 12605, Napoleon testnet 20605
Network magicmainnet ec e7 ef f3, testnet ec f4 f3 f4, regtest ec f2 e5 e7, Napoleon testnet ec ee e1 f0
Message header4-byte magic, 12-byte command, u32 payload length, 4-byte checksum (first bytes of SHA256d of the payload)
Block header160 bytes, hashed with LotusHash: see Block header
Transaction idNot the hash of the bytes: see Transaction id
WebSocketThe same messages, one per binary frame, at ws://<node>:10605/p2p or wss://... (browsers)
EncryptionOptional, negotiated by the node that dials: see Encrypted P2P

The version message is Bitcoin's with one extra field at the end: u64 nExtraEntropy. A client that sets the relay flag to 0 gets no transaction announcements.

User agents #

Lotus software announces itself in the user agent, and nodes classify peers by it (see Network map API).

SoftwareUser agent
Full node/lotusd:12.5.9(EB32.0)/
Thin node/lotusd:12.5.9-thin(EB32.0)/
Browser library/lotusd:12.5.9-browser(lotus-node.js 0.3.0)/
RANK extension/lotusd:12.5.8-browser(lotus-node.js 0.2.0; extension 0.2.1)/
Lotus Desktop/lotus-desktop:12.5.9/
Lotus mobile app/lotus-desktop:<v>(lotus-mobile <v>; ...)/

Use a user agent of your own (/my-wallet:1.0/). Do not imitate /lotusd:: nodes count only full nodes in software shares and in the upgrade notice quorum, and they decide which optional messages to send to a peer from its user agent.

Messages a client receives #

Right after verack, a 12.5.9 full node sends, in this order (seen on mainnet and regtest):

MessagePayloadWhat it offersIf you do not support it
sendaddrv2emptyBIP155 addressesIgnore
sendzstdu32 version, u64 flagsIt accepts zstd-compressed messages from you. It compresses to you only if you send sendzstd tooIgnore
sendheightu32 1It wants your height messages (i32 tip height)Ignore
sendphdrsu32 1Parent-chain header relay (merged mining)Ignore
sendlanesu32 1It answers getlanes (difficulty lanes, for thin agents)Ignore
sendaddrqu32 1It answers getaddrtxs (below)Ignore
sendheaders, sendcmpctstandardBIP130, BIP152Standard
upgnotice16 bytes: format 1, page id, u16 major, minor, patch, i64 required before (median time past, 0 = none)The release the node runs or announcesIgnore. It is never relayed
pingu64 nonceAnswer pongRequired, as in Bitcoin
inv or headersstandardIts tipStandard

Other Lotus messages go only to peers that asked for them, or to fleet peers: voicehello (VOIX, to lotusd 12.5.9+, lotus-node.js 0.3.0+, Lotus Desktop 0.2.0+), selflinks/selflinksok (browser and desktop apps), getlinks/links (to peers advertising the mesh service bit 27), pool messages (trusted fleet peers only), holdparam.

Warning

Skip any message you do not know. Read the header, drop the payload, carry on. A client that disconnects on an unknown command cannot talk to Lotus nodes: new optional messages come with most releases. Nodes do the same for yours: an unknown message costs no misbehaviour score.

What does cost a score: a non-version message before version (10), a message other than version/verack before verack (10), a malformed upgnotice (10), a malformed or oversized getaddrtxs (20).

Address query with proofs #

A light wallet needs the transactions of its addresses. Since 12.5.9 every full node answers that over P2P, by default, with a merkle proof for each transaction, so a client can check each one against a header it verified and compare several nodes instead of trusting one server.

What it proves #

StatementGuarantee
A listed transaction is in the chain at that heightProven by its merkle branch against a header you verified
It concerns the scriptChecked on the transaction itself
A coin is spentProven: the spender is in the list
Nothing was left out; a coin is unspentOnly if at least one of the nodes you ask is honest. A node whose list lacks an entry another node proved is caught
Unconfirmed transactionsNot covered

The nodes you ask learn the scripts you ask for, your IP address and when.

Messages #

All little-endian, Bitcoin serialization. A node offers the service with sendaddrq; ask only peers that sent it.

getaddrtxs:

Text
u16  version        1
u64  reqid          echoed in the answer
u8   flags          1 WANT_TXS: attach each transaction and its branch
                    2 DIGEST_ONLY: count and digest only (not both)
hash stop           a block of your verified chain: entries up to its height
u16  limit          1 to 1000 index rows per script
compactsize n       1 to 32 scripts, n x limit at most 8000
n x { varbytes script (scriptPubKey, 1 to 128 bytes)
      i32 after_height (-1 to start), u8 has_txid, [hash after_txid] }

addrtxs:

Text
u16  version, u64 reqid
u8   status         0 OK, 1 RETRY (stop not on its best chain, or syncing), 2 BUSY
hash block          OK: stop; otherwise its tip
i32  height
-- OK only --
compactsize n, n x {
  u8 flags          1 MORE (ask again from next), 2 NO_ADDRESS (nothing can be said)
  compactsize count
  [hash digest]     if count > 0: SHA256d of count x (i32 height || 32-byte txid)
  [i32 next_height, hash next_txid]   with MORE
  compactsize listed   0 with DIGEST_ONLY, else count
  listed x { i32 height, hash txid, u8 has_tx,
             [u32 index, tx, compactsize m, m x hash branch] }
}

Entries are ordered by height, then txid bytes. To check a proof: leaf = SHA256d(SHA256d(tx) || txid); fold the branch from index, bit 0 first, a set bit meaning the sibling is on the left; the result must be the merkle root of the header at height. index is 0 exactly for a coinbase. With WANT_TXS a node attaches proofs until about 1 MB of answer; later entries come with has_tx 0, and you ask again from the last proven one.

Limits per peer: 20 scripts a second, burst 600 (a script costs 3 with WANT_TXS), 4 requests waiting; BUSY beyond. RETRY and BUSY are not offences: ask another node. -addrquery=0 turns the service off on a node; thin and pruned nodes do not offer it. A node's counters are under addrquery in GET /api/v1/network.

A client you can run #

This Python script (standard library only) connects to a node, does the handshake while skipping every message it does not need, asks for the transactions of one script with proofs, checks each transaction's id and merkle branch, and checks the page digest. To stay short it takes the merkle roots from a REST API; a real light client checks them against headers it verified itself.

Shell
# Mainnet, read-only: the first 5 transactions of an address
python3 addrq.py seed.givelotus.org 10605 mainnet \
  76a91457c67658d282726af1f68e5cd2bd13b3c18b9bdd88ac https://givelotus.org/api/v1 5
# Your regtest node
python3 addrq.py 127.0.0.1 12605 regtest <scriptPubKey hex> http://127.0.0.1:12604/api/v1
JSON
{"status": 0, "block": "0000000000e9ac9a69c67e8ae65ee025b6a356397d79bdd1a8dcf491cd0dbfb9", "height": 1433879}
{"height": 1432292, "txid": "fc3c049494c53b010d238a7e2d09af9508b310d5acdf14645416a514b3582dc0", "index": 0, "branch": 0, "proof_ok": true}

The scriptPubKey of an address: GET /api/v1/rpc/validateaddress?0=<address>.

Python
# addrq.py
#!/usr/bin/env python3
"""Ask a Lotus node for the transactions of one address over P2P
(getaddrtxs, 12.5.9) and check every merkle proof against a block header.

    python3 addrq.py HOST PORT NETWORK SCRIPT_HEX REST_BASE [LIMIT]

A real light client checks the proofs against headers it verified itself;
this example takes the stop block and the merkle roots from a node's REST
API (REST_BASE, for example http://127.0.0.1:12604/api/v1) to stay short.
"""
import hashlib, json, os, socket, struct, sys, time, urllib.request

MAGIC = {"mainnet": "ece7eff3", "testnet": "ecf4f3f4", "regtest": "ecf2e5e7",
         "napoleontest": "eceee1f0"}


def sha256d(b):
    return hashlib.sha256(hashlib.sha256(b).digest()).digest()


def compact(n):
    if n < 0xfd: return bytes([n])
    if n <= 0xffff: return b"\xfd" + struct.pack("<H", n)
    if n <= 0xffffffff: return b"\xfe" + struct.pack("<I", n)
    return b"\xff" + struct.pack("<Q", n)


class R:
    def __init__(s, b): s.b, s.i = b, 0
    def take(s, n):
        v = s.b[s.i:s.i + n]; s.i += n
        if len(v) != n: raise ValueError("short message")
        return v
    def u(s, fmt): return struct.unpack("<" + fmt, s.take(struct.calcsize(fmt)))[0]
    def cs(s):
        n = s.take(1)[0]
        return n if n < 0xfd else s.u({0xfd: "H", 0xfe: "I", 0xff: "Q"}[n])
    def var(s): return s.take(s.cs())


def merkle_root(leaves):
    """Lotus merkle tree: an odd level is completed with a zero hash."""
    if not leaves: return b"\0" * 32
    while len(leaves) > 1:
        if len(leaves) % 2: leaves.append(b"\0" * 32)
        leaves = [sha256d(leaves[i] + leaves[i + 1]) for i in range(0, len(leaves), 2)]
    return leaves[0]


def read_tx(r):
    """Reads one serialized transaction; returns (raw, txhash, txid)."""
    start = r.i
    version = r.take(4)
    ins = []
    for _ in range(r.cs()):
        prevout = r.take(36); r.var(); seq = r.take(4)
        ins.append(sha256d(prevout + seq))
    outs = []
    for _ in range(r.cs()):
        a = r.i; r.take(8); r.var(); outs.append(sha256d(r.b[a:r.i]))
    locktime = r.take(4)
    raw = r.b[start:r.i]
    height = lambda n: 0 if n == 0 else (n - 1).bit_length() + 1
    # Lotus txid: version, inputs root and height, outputs root and height,
    # lock time (share/www/docs/txid.md).
    pre = (version + merkle_root(ins) + bytes([height(len(ins))]) +
           merkle_root(outs) + bytes([height(len(outs))]) + locktime)
    return raw, sha256d(raw), sha256d(pre)


def msg(magic, cmd, payload=b""):
    return (magic + cmd.encode().ljust(12, b"\0") + struct.pack("<I", len(payload))
            + sha256d(payload)[:4] + payload)


def recv(sock, magic):
    def exact(n):
        b = b""
        while len(b) < n:
            c = sock.recv(n - len(b))
            if not c: raise ConnectionError("closed")
            b += c
        return b
    h = exact(24)
    assert h[:4] == magic, "wrong network"
    cmd = h[4:16].rstrip(b"\0").decode()
    n = struct.unpack("<I", h[16:20])[0]
    return cmd, exact(n)


def main():
    host, port, net, script_hex, rest = sys.argv[1:6]
    limit = int(sys.argv[6]) if len(sys.argv) > 6 else 50  # rows, 1 to 1000
    magic = bytes.fromhex(MAGIC[net])
    script = bytes.fromhex(script_hex)
    s = socket.create_connection((host, int(port)), timeout=30)
    addr = struct.pack("<Q", 0) + b"\0" * 10 + b"\xff\xff" + b"\0" * 4 + struct.pack(">H", 0)
    ua = b"/addrq-example:0.1/"
    version = (struct.pack("<iQq", 70016, 0, int(time.time())) + addr + addr +
               os.urandom(8) + compact(len(ua)) + ua + struct.pack("<i", 0) +
               b"\x00" + os.urandom(8))  # relay 0, extra entropy
    s.sendall(msg(magic, "version", version))
    offered, ready, tip = False, False, None
    while not ready:
        cmd, p = recv(s, magic)
        if cmd == "version":
            s.sendall(msg(magic, "verack"))
        elif cmd == "verack":
            pass
        elif cmd == "sendaddrq":
            offered = True
        elif cmd == "ping":
            s.sendall(msg(magic, "pong", p))
        elif cmd == "inv" and p[1:5] == b"\x02\0\0\0":
            tip = p[5:37]  # the node announced its tip: use it as the stop block
            ready = True
        # Every other message (sendzstd, sendheight, sendlanes, upgnotice,
        # sendheaders, sendcmpct, feefilter...) is skipped: a P2P client must
        # ignore what it does not know.
        print("<-", cmd, len(p), "bytes", file=sys.stderr)
    assert offered, "this node does not answer getaddrtxs"
    get = lambda path: json.load(urllib.request.urlopen(urllib.request.Request(
        rest + path, headers={"User-Agent": "addrq-example/0.1"})))

    def merkle_root_at(h):
        bh = get("/rpc/getblockhash?0=%d" % h)["result"]
        return get("/rpc/getblockheader?0=" + bh)["result"]["merkleroot"]

    stop = tip or bytes.fromhex(get("/chain/tip")["hash"])[::-1]  # internal byte order
    req = (struct.pack("<HQB", 1, 7, 1) + stop + struct.pack("<H", limit) +
           compact(1) + compact(len(script)) + script + struct.pack("<iB", -1, 0))
    s.sendall(msg(magic, "getaddrtxs", req))
    while True:
        cmd, p = recv(s, magic)
        if cmd == "ping": s.sendall(msg(magic, "pong", p))
        if cmd == "addrtxs": break
    r = R(p)
    ver, reqid, status = r.u("H"), r.u("Q"), r.u("B")
    block, height = r.take(32)[::-1].hex(), r.u("i")
    print(json.dumps({"status": status, "block": block, "height": height}))
    if status != 0: return
    for _ in range(r.cs()):
        flags, count = r.u("B"), r.cs()
        digest = r.take(32) if count else None
        if flags & 1: r.u("i"); r.take(32)
        entries = []
        for _ in range(r.cs()):
            h, txid = r.u("i"), r.take(32)
            entries.append(struct.pack("<i", h) + txid)
            if not r.u("B"):
                print(json.dumps({"height": h, "txid": txid[::-1].hex(), "proof": None}))
                continue
            index = r.u("I")
            raw, txhash, own_txid = read_tx(r)
            branch = [r.take(32) for _ in range(r.cs())]
            assert own_txid == txid, "the transaction does not hash to the txid"
            node = sha256d(txhash + txid)
            for level, sib in enumerate(branch):
                node = sha256d(sib + node) if (index >> level) & 1 else sha256d(node + sib)
            ok = node[::-1].hex() == merkle_root_at(h)
            print(json.dumps({"height": h, "txid": txid[::-1].hex(), "index": index,
                              "branch": len(branch), "proof_ok": ok}))
        if count:
            assert sha256d(b"".join(entries)) == digest, "the page digest does not match"


if __name__ == "__main__":
    main()

Light clients after Napoleon #

From the Napoleon activation (median time past 1797886200), a block may be proven by a parent-chain header (Bitcoin or Litecoin, merged mining) carried in its metadata instead of by its own hash. A header-only client that checks LotusHash(header) <= target refuses such blocks and stops following the chain. What each kind of client does:

ClientAfter Napoleon
Your own header-only clientMust fetch the block (or its metadata, getblkmeta) of a header whose own hash does not meet the target, and check the parent proof: see Merged mining and Block header
lotus-node.js (browser)Does this: fetches the block, checks the parent's work, the commitment to this block and the anchor. Three rules that need the parent chains' history stay with full nodes (parentContext: 'unchecked')
Lotus Desktop, the phone appCheck headers and parent proofs, and the structure of recent blocks; not scripts or coins
lotusd thin or pruned, started after NapoleonRebuilds the parent-chain context it lacks from its own blocks and from peers (getblkmeta, answers checked against the block hashes), then checks and produces blocks like a full node. Until a peer serves it, it follows the chain and refuses block templates; getblockchaininfo shows parent_context (active, checked)

Thin clients of 12.5.9 also relay other people's transactions only when full nodes in two network groups announced them and two of them served the same bytes ("vouched relay"), and never relay a block.

Source share/www/docs/p2p.md in the lotusd repository
Checked against src/protocol.h src/protocol.cpp src/version.h src/net_processing.cpp src/peerkind.h src/proofs/addrquery.h doc/address-query.md doc/upgrade-notice.md doc/network-mesh.md test/functional/test_framework/messages.py test/functional/test_framework/p2p.py