Skip to content

Commit daa4ec4

Browse files
implement libp2p
1 parent 5ec7c0b commit daa4ec4

4 files changed

Lines changed: 152 additions & 401 deletions

File tree

main.py

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33
44
Usage:
55
python main.py --port 9000
6-
python main.py --port 9001 --connect 127.0.0.1:9000
6+
python main.py --port 9001 --connect <multiaddress>
77
88
Commands (type in the terminal while the node is running):
99
balance — show all account balances
1010
send <to> <amount> — send coins to another address
1111
mine — mine a block from the mempool
1212
peers — show connected peers
13-
connect <host>:<port> — connect to another node
13+
connect <multiaddr> — connect to another node
1414
address — show this node's public key
1515
help — show available commands
1616
quit — shut down the node
@@ -147,12 +147,19 @@ async def handler(data):
147147
logger.info("🔄 Accepted state sync from %s — %d accounts", peer_addr, len(chain.state.accounts))
148148

149149
elif msg_type == "tx":
150-
tx = Transaction.from_dict(payload)
151-
if mempool.add_transaction(tx):
152-
logger.info("📥 Received tx from %s... (amount=%s)", tx.sender[:8], tx.amount)
150+
try:
151+
tx = Transaction.from_dict(payload)
152+
if mempool.add_transaction(tx):
153+
logger.info("📥 Received tx from %s... (amount=%s)", tx.sender[:8], tx.amount)
154+
except Exception as e:
155+
logger.warning("Invalid tx payload from %s: %s", peer_addr, e)
153156

154157
elif msg_type == "block":
155-
block = Block.from_dict(payload)
158+
try:
159+
block = Block.from_dict(payload)
160+
except Exception as e:
161+
logger.warning("Invalid block payload from %s: %s", peer_addr, e)
162+
return
156163

157164
if chain.add_block(block):
158165
logger.info("📥 Received Block #%d — added to chain", block.index)
@@ -350,19 +357,14 @@ async def cli_loop(sk, pk, chain, mempool, network):
350357
# ── connect ──
351358
elif cmd == "connect":
352359
if len(parts) < 2:
353-
print(" Usage: connect <host>:<port>")
360+
print(" Usage: connect <multiaddress>")
354361
continue
355-
try:
356-
host, port_str = parts[1].rsplit(":", 1)
357-
port = int(port_str)
358-
except ValueError:
359-
print(" Invalid format. Use host:port")
360-
continue
361-
success = await network.connect_to_peer(host, port)
362+
maddr_str = parts[1]
363+
success = await network.connect_to_peer(maddr_str)
362364
if success:
363-
print(f" Connected to {host}:{port}")
365+
print(f" Attempting to dial {maddr_str}...")
364366
else:
365-
print(f" Failed to connect to {host}:{port}")
367+
print(f" Failed to initiate connection to {maddr_str}")
366368

367369
# ── address ──
368370
elif cmd == "address":
@@ -447,11 +449,7 @@ async def on_peer_connected(writer):
447449

448450
# Connect to a seed peer if requested
449451
if connect_to:
450-
try:
451-
host, peer_port = connect_to.rsplit(":", 1)
452-
await network.connect_to_peer(host, int(peer_port))
453-
except ValueError:
454-
logger.error("Invalid --connect format. Use host:port")
452+
await network.connect_to_peer(connect_to)
455453

456454
try:
457455
await cli_loop(sk, pk, chain, mempool, network)
@@ -474,7 +472,7 @@ def main():
474472
parser = argparse.ArgumentParser(description="MiniChain Node — Testnet Demo")
475473
parser.add_argument("--host", type=str, default="127.0.0.1", help="Host/IP to bind the P2P server (default: 127.0.0.1)")
476474
parser.add_argument("--port", type=int, default=9000, help="TCP port to listen on (default: 9000)")
477-
parser.add_argument("--connect", type=str, default=None, help="Peer address to connect to (host:port)")
475+
parser.add_argument("--connect", type=str, default=None, help="Peer address to connect to (multiaddr)")
478476
parser.add_argument("--fund", type=int, default=100, help="Initial coins to fund this wallet (default: 100)")
479477
parser.add_argument("--datadir", type=str, default=None, help="Directory to save/load blockchain state (enables persistence)")
480478
args = parser.parse_args()

0 commit comments

Comments
 (0)