Verify messages with Agents
Introduction
This file can be run on any platform supporting Python, with the necessary install permissions. This example shows how to use Agents to make them verify authenticity of messages sent with one another.
Please check out the example code in our examples repo (opens in a new tab) to run this locally.
Supporting documentation
- Creating an agent
- Communicating with other agents
- Register in Almanac
- Almanac Contract
- Protocols
- How to use agents to verify messages
The agent
Self hosted
message_verification.pyimport hashlib from uagents import Agent, Bureau, Context, Model from uagents.crypto import Identity class Message(Model): message: str digest: str signature: str def encode(message: str) -> bytes: hasher = hashlib.sha256() hasher.update(message.encode()) return hasher.digest() alice = Agent(name="alice", seed="alice recovery password") bob = Agent(name="bob", seed="bob recovery password") @alice.on_interval(period=3.0) async def send_message(ctx: Context): msg = "hello there bob" digest = encode(msg) await ctx.send( bob.address, Message(message=msg, digest=digest.hex(), signature=alice.sign_digest(digest)), ) @alice.on_message(model=Message) async def alice_rx_message(ctx: Context, sender: str, msg: Message): assert Identity.verify_digest( sender, bytes.fromhex(msg.digest), msg.signature ), "couldn't verify bob's message" ctx.logger.info("Bob's message verified!") ctx.logger.info(f"Received message from {sender}: {msg.message}") @bob.on_message(model=Message) async def bob_rx_message(ctx: Context, sender: str, msg: Message): assert Identity.verify_digest( sender, bytes.fromhex(msg.digest), msg.signature ), "couldn't verify alice's message" ctx.logger.info("Alice's message verified!") ctx.logger.info(f"Received message from {sender}: {msg.message}") msg = "hello there alice" digest = encode(msg) await ctx.send( alice.address, Message(message=msg, digest=digest.hex(), signature=bob.sign_digest(digest)), ) bureau = Bureau() bureau.add(alice) bureau.add(bob) if __name__ == "__main__": bureau.run()
Expected output
[ bob]: Alice's message verified! [ bob]: Received message from agent1qf5gfqm48k9acegez3sg82ney2aa6l5fvpwh3n3z0ajh0nam3ssgwnn5me7: hello there bob [alice]: Bob's message verified! [alice]: Received message from agent1qvjjle8dlf22ff7zsh6wr3gl8tdepzygftdxpc2vn8539ngt962a709c90s: hello there alice