import sys
import grpc
try:
from ipfrs.block.v1 import block_pb2, block_pb2_grpc
except ImportError:
print("Error: gRPC proto files not generated.")
print("\nPlease run:")
print(" python -m grpc_tools.protoc -I../proto --python_out=. --grpc_python_out=. \\")
print(" ../proto/block.proto ../proto/dag.proto ../proto/file.proto ../proto/tensor.proto")
sys.exit(1)
def run():
print("Connecting to IPFRS gRPC Server...")
channel = grpc.insecure_channel('[::1]:50051')
stub = block_pb2_grpc.BlockServiceStub(channel)
print("✓ Connected to server\n")
print("Example 1: Storing a block")
data = b"Hello, IPFRS gRPC from Python!"
request = block_pb2.PutBlockRequest(data=data, cid="")
response = stub.PutBlock(request)
if response.HasField('error'):
print(f"Error: {response.error.message}")
return
cid = response.cid
print(f" ✓ Block stored with CID: {cid}")
print(f" Size: {len(data)} bytes\n")
print("Example 2: Checking if block exists")
request = block_pb2.HasBlockRequest(cid=cid)
response = stub.HasBlock(request)
if response.HasField('error'):
print(f"Error: {response.error.message}")
return
print(f" ✓ Block exists: {response.exists}\n")
print("Example 3: Retrieving the block")
request = block_pb2.GetBlockRequest(cid=cid)
response = stub.GetBlock(request)
if response.HasField('error'):
print(f"Error: {response.error.message}")
return
retrieved_data = response.data
print(f" ✓ Retrieved data: {retrieved_data.decode('utf-8')}")
print(f" CID: {response.cid}")
print(f" Size: {response.size} bytes\n")
if retrieved_data == data:
print("✓ Success! Data matches original")
else:
print("✗ Error: Data mismatch")
print("\nExample 4: Batch operations")
cids = [cid] request = block_pb2.BatchGetBlocksRequest(cids=cids)
print(" Retrieving blocks in batch...")
for response in stub.BatchGetBlocks(request):
if response.HasField('error'):
print(f" Error: {response.error.message}")
continue
print(f" ✓ Retrieved CID: {response.cid} ({response.size} bytes)")
print("\n✓ All examples completed successfully!")
if __name__ == '__main__':
run()