importjsonimportosimporttimeimporturllib.errorimporturllib.requestfrombinasciiimporthexlifyfromsymbolchain.CryptoTypesimportPrivateKey,PublicKeyfromsymbolchain.facade.NemFacadeimportNemFacadefromsymbolchain.ncimportAmount,Message,MessageTypefromsymbolchain.nem.FeeCalculatorimportcalculate_transaction_feefromsymbolchain.nem.MessageEncoderimportMessageEncoder# ConfigurationNODE_URL=os.getenv('NODE_URL','http://libertalia.nemtest.net:7890')print(f'Using node {NODE_URL}')# Helper function to wait for transaction confirmationdefwait_for_confirmation(tx_hash,label):status_path=f'/transaction/get?hash={tx_hash}'print(f'Waiting for {label} confirmation from {status_path}')is_confirmed=Falseconfirmed=Nonefor_inrange(120):try:withurllib.request.urlopen(f'{NODE_URL}{status_path}')asstatus_response:confirmed=json.loads(status_response.read().decode())height=confirmed['meta']['height']print(f'{label} confirmed in block {height}')is_confirmed=Truebreakexcepturllib.error.HTTPError:print(' Transaction status: pending')time.sleep(1)ifnotis_confirmed:print(f'{label} confirmation took too long.')returnconfirmed# Set up sender and recipient accountsfacade=NemFacade('testnet')sender_private_key_string=os.getenv('SENDER_PRIVATE_KEY','0000000000000000000000000000000000000000000000000000000000000000',)sender_key_pair=NemFacade.KeyPair(PrivateKey(sender_private_key_string))sender_address=facade.network.public_key_to_address(sender_key_pair.public_key)recipient_private_key_string=os.getenv('RECIPIENT_PRIVATE_KEY','1111111111111111111111111111111111111111111111111111111111111111',)recipient_key_pair=NemFacade.KeyPair(PrivateKey(recipient_private_key_string))recipient_address=facade.network.public_key_to_address(recipient_key_pair.public_key)print(f'Sender address: {sender_address}')print(f'Recipient address: {recipient_address}\n')# --- PLAIN TEXT MESSAGE ---print('==> Sending Plain Text Message')# Create a plain text messageplain_message='Hello, NEM!'.encode('utf-8')print(f'Plain message: {plain_message.decode("utf-8")}')# Build transfer transaction with plain messageplain_transaction=facade.create_transaction_from_descriptor({'type':'transfer_transaction_v2','recipient_address':recipient_address,'amount':0,'message':{'message_type':'plain','message':plain_message,},},sender_key_pair.public_key,0,2*60*60)plain_transaction.fee=Amount(calculate_transaction_fee(plain_transaction))# Sign and announce the transactionplain_signature=facade.sign_transaction(sender_key_pair,plain_transaction)plain_json_payload=facade.transaction_factory.attach_signature(plain_transaction,plain_signature)plain_transaction_hash=facade.hash_transaction(plain_transaction)print(f'Transaction hash: {plain_transaction_hash}')plain_announce_request=urllib.request.Request(f'{NODE_URL}/transaction/announce',data=plain_json_payload.encode('utf-8'),headers={'Content-Type':'application/json'},method='POST',)withurllib.request.urlopen(plain_announce_request)asresponse:print('Plain message transaction announced\n')# --- RECEIVING PLAIN TEXT MESSAGE ---print('<== Receiving Plain Text Message')# Wait for confirmationplain_tx_data=wait_for_confirmation(plain_transaction_hash,'Plain message transaction')# Decode plain message from confirmed transactionreceived_plain_message=bytes.fromhex(plain_tx_data['transaction']['message']['payload'])print(f'Received plain message: {received_plain_message.decode("utf-8")}\n')# --- ENCRYPTED MESSAGE ---print('==> Sending Encrypted Message')# Create a message encoder with sender's key pairsender_message_encoder=MessageEncoder(sender_key_pair)# Encrypt the message using recipient's public keysecret_message='This is a secret message!'.encode('utf-8')encrypted_message=sender_message_encoder.encode(recipient_key_pair.public_key,secret_message)print(f'Original message: {secret_message.decode("utf-8")}')encrypted_payload=hexlify(encrypted_message.message).decode('utf-8')print(f'Encrypted payload: {encrypted_payload}')# Build transfer transaction with encrypted messageencrypted_transaction=facade.create_transaction_from_descriptor({'type':'transfer_transaction_v2','recipient_address':recipient_address,'amount':0,'message':{'message_type':'encrypted','message':encrypted_message.message,},},sender_key_pair.public_key,0,2*60*60)encrypted_transaction.fee=Amount(calculate_transaction_fee(encrypted_transaction))# Sign and announce the transactionencrypted_signature=facade.sign_transaction(sender_key_pair,encrypted_transaction)encrypted_json_payload=facade.transaction_factory.attach_signature(encrypted_transaction,encrypted_signature)encrypted_transaction_hash=facade.hash_transaction(encrypted_transaction)print(f'Transaction hash: {encrypted_transaction_hash}')encrypted_announce_request=urllib.request.Request(f'{NODE_URL}/transaction/announce',data=encrypted_json_payload.encode('utf-8'),headers={'Content-Type':'application/json'},method='POST',)withurllib.request.urlopen(encrypted_announce_request)asresponse:print('Encrypted message transaction announced\n')# --- RECEIVING ENCRYPTED MESSAGE ---print('<== Receiving Encrypted Message')# Wait for confirmationencrypted_tx_data=wait_for_confirmation(encrypted_transaction_hash,'Encrypted message transaction')# Decode encrypted message using recipient's private keyrecipient_message_encoder=MessageEncoder(recipient_key_pair)received_encrypted_message=Message()received_encrypted_message.message_type=MessageType.ENCRYPTEDreceived_encrypted_message.message=bytes.fromhex(encrypted_tx_data['transaction']['message']['payload'])# Get sender's public key from the transactionsender_public_key_from_tx=PublicKey(encrypted_tx_data['transaction']['signer'])(is_decoded,decrypted_message)=recipient_message_encoder.try_decode(sender_public_key_from_tx,received_encrypted_message)ifis_decoded:message_text=decrypted_message.decode('utf-8')print(f'Recipient decrypted message: {message_text}')else:print('Recipient failed to decrypt message')
import{PrivateKey,PublicKey}from'symbol-sdk';import{Address,MessageEncoder,NemFacade,calculateTransactionFee,descriptors,models}from'symbol-sdk/nem';// ConfigurationconstNODE_URL=process.env.NODE_URL||'http://libertalia.nemtest.net:7890';console.log('Using node',NODE_URL);// Helper function to wait for transaction confirmationasyncfunctionwaitForConfirmation(transactionHash,label){conststatusPath=`/transaction/get?hash=${transactionHash}`;console.log(`Waiting for ${label} confirmation from`,statusPath);letisConfirmed=false;letconfirmed;for(letattempt=1;120>=attempt;++attempt){constresponse=awaitfetch(`${NODE_URL}${statusPath}`);if(!response.ok){console.log(' Transaction status: pending');awaitnewPromise(resolve=>{setTimeout(resolve,1000);});}else{confirmed=awaitresponse.json();console.log(`${label} confirmed in block`,confirmed.meta.height);isConfirmed=true;break;}}if(!isConfirmed)console.warn(`${label} confirmation took too long.`);returnconfirmed;}// Set up sender and recipient accountsconstfacade=newNemFacade('testnet');constsenderPrivateKeyString=process.env.SENDER_PRIVATE_KEY||'0000000000000000000000000000000000000000000000000000000000000000';constsenderKeyPair=newNemFacade.KeyPair(newPrivateKey(senderPrivateKeyString));constsenderAddress=facade.network.publicKeyToAddress(senderKeyPair.publicKey);constrecipientPrivateKeyString=process.env.RECIPIENT_PRIVATE_KEY||'1111111111111111111111111111111111111111111111111111111111111111';constrecipientKeyPair=newNemFacade.KeyPair(newPrivateKey(recipientPrivateKeyString));constrecipientAddress=facade.network.publicKeyToAddress(recipientKeyPair.publicKey);console.log('Sender address:',senderAddress.toString());console.log('Recipient address:',recipientAddress.toString(),'\n');// --- PLAIN TEXT MESSAGE ---console.log('==> Sending Plain Text Message');// Create a plain text messageconstplainMessage=newTextEncoder().encode('Hello, NEM!');console.log('Plain message:',newTextDecoder().decode(plainMessage));// Build transfer transaction with plain messageconstplainTransaction=facade.createTransactionFromTypedDescriptor(newdescriptors.TransferTransactionV2Descriptor(newAddress(recipientAddress.toString()),newmodels.Amount(0n),newdescriptors.MessageDescriptor(models.MessageType.PLAIN,plainMessage)),senderKeyPair.publicKey,0n,2*60*60);plainTransaction.fee=newmodels.Amount(calculateTransactionFee(plainTransaction));// Sign and announce the transactionconstplainSignature=facade.signTransaction(senderKeyPair,plainTransaction);constplainJsonPayload=facade.transactionFactory.static.attachSignature(plainTransaction,plainSignature);constplainTransactionHash=facade.hashTransaction(plainTransaction).toString();console.log('Transaction hash:',plainTransactionHash);awaitfetch(`${NODE_URL}/transaction/announce`,{method:'POST',headers:{'Content-Type':'application/json'},body:plainJsonPayload});console.log('Plain message transaction announced\n');// --- RECEIVING PLAIN TEXT MESSAGE ---console.log('<== Receiving Plain Text Message');// Wait for confirmationconstplainTxData=awaitwaitForConfirmation(plainTransactionHash,'Plain message transaction');// Decode plain message from confirmed transactionconstreceivedPlainMessage=Buffer.from(plainTxData.transaction.message.payload,'hex');console.log('Received plain message:',newTextDecoder().decode(receivedPlainMessage),'\n');// --- ENCRYPTED MESSAGE ---console.log('==> Sending Encrypted Message');// Create a message encoder with sender's key pairconstsenderMessageEncoder=newMessageEncoder(senderKeyPair);// Encrypt the message using recipient's public keyconstsecretMessage=newTextEncoder().encode('This is a secret message!');constencryptedMessage=senderMessageEncoder.encode(recipientKeyPair.publicKey,secretMessage);console.log('Original message:',newTextDecoder().decode(secretMessage));console.log('Encrypted payload:',Buffer.from(encryptedMessage.message).toString('hex'));// Build transfer transaction with encrypted messageconstencryptedTransaction=facade.createTransactionFromTypedDescriptor(newdescriptors.TransferTransactionV2Descriptor(newAddress(recipientAddress.toString()),newmodels.Amount(0n),newdescriptors.MessageDescriptor(models.MessageType.ENCRYPTED,encryptedMessage.message)),senderKeyPair.publicKey,0n,2*60*60);encryptedTransaction.fee=newmodels.Amount(calculateTransactionFee(encryptedTransaction));// Sign and announce the transactionconstencryptedSignature=facade.signTransaction(senderKeyPair,encryptedTransaction);constencryptedJsonPayload=facade.transactionFactory.static.attachSignature(encryptedTransaction,encryptedSignature);constencryptedTransactionHash=facade.hashTransaction(encryptedTransaction).toString();console.log('Transaction hash:',encryptedTransactionHash);awaitfetch(`${NODE_URL}/transaction/announce`,{method:'POST',headers:{'Content-Type':'application/json'},body:encryptedJsonPayload});console.log('Encrypted message transaction announced\n');// --- RECEIVING ENCRYPTED MESSAGE ---console.log('<== Receiving Encrypted Message');// Wait for confirmationconstencryptedTxData=awaitwaitForConfirmation(encryptedTransactionHash,'Encrypted message transaction');// Decode encrypted message using recipient's private keyconstrecipientMessageEncoder=newMessageEncoder(recipientKeyPair);constreceivedEncryptedMessage=newmodels.Message();receivedEncryptedMessage.messageType=models.MessageType.ENCRYPTED;receivedEncryptedMessage.message=Buffer.from(encryptedTxData.transaction.message.payload,'hex');// Get sender's public key from the transactionconstsenderPublicKeyFromTx=newPublicKey(encryptedTxData.transaction.signer);constresult=recipientMessageEncoder.tryDecode(senderPublicKeyFromTx,receivedEncryptedMessage);if(result.isDecoded){console.log('Recipient decrypted message:',newTextDecoder().decode(result.message));}else{console.log('Recipient failed to decrypt message');}
//JAVA 21+//DEPS org.symbol:symbol-sdk:3.3.3import staticjava.nio.charset.StandardCharsets.UTF_8;importjava.io.IOException;importjava.net.URI;importjava.net.http.HttpClient;importjava.net.http.HttpRequest;importjava.net.http.HttpResponse;importjava.net.http.HttpResponse.BodyHandlers;importjava.util.HexFormat;importjava.util.List;importcom.fasterxml.jackson.databind.JsonNode;importcom.fasterxml.jackson.databind.ObjectMapper;importorg.symbol.sdk.CryptoTypes;importorg.symbol.sdk.MessageEncoderResult;importorg.symbol.sdk.facade.NemFacade;importorg.symbol.sdk.nem.Address;importorg.symbol.sdk.nem.FeeCalculator;importorg.symbol.sdk.nem.KeyPair;importorg.symbol.sdk.nem.MessageEncoder;importorg.symbol.sdk.nem.NemTransactionFactory;importorg.symbol.sdk.nem.descriptors.*;importorg.symbol.sdk.nem.models.Amount;importorg.symbol.sdk.nem.models.Message;importorg.symbol.sdk.nem.models.MessageType;importorg.symbol.sdk.nem.models.Transaction;publicfinalclassMessages{privatestaticfinalObjectMapperJSON_MAPPER=newObjectMapper();privatestaticfinalHttpClientHTTP_CLIENT=HttpClient.newHttpClient();// ConfigurationprivatefinalStringnodeUrl=System.getenv().getOrDefault("NODE_URL","http://libertalia.nemtest.net:7890");privatefinalNemFacadefacade=newNemFacade("testnet");privateJsonNodewaitForConfirmation(finalStringtransactionHash,finalStringlabel)throwsIOException,InterruptedException{finalStringstatusPath=String.format("/transaction/get?hash=%s",transactionHash);System.out.printf("Waiting for %s confirmation from %s%n",label,statusPath);booleanisConfirmed=false;JsonNodeconfirmed=null;for(intattempt=1;120>=attempt;++attempt){finalHttpRequestrequest=HttpRequest.newBuilder(URI.create(nodeUrl+statusPath)).GET().build();finalHttpResponse<String>response=HTTP_CLIENT.send(request,BodyHandlers.ofString());if(2!=response.statusCode()/100){System.out.println(" Transaction status: pending");Thread.sleep(1000);}else{confirmed=JSON_MAPPER.readTree(response.body());System.out.printf("%s confirmed in block %s%n",label,confirmed.get("meta").get("height").asText());isConfirmed=true;break;}}if(!isConfirmed)System.out.printf("%s confirmation took too long.%n",label);returnconfirmed;}publicstaticvoidmain(finalString[]args){try{newMessages().run();}catch(finalExceptionex){System.out.println(null==ex.getMessage()?ex.toString():ex.getMessage());}}privatevoidrun()throwsIOException,InterruptedException{System.out.printf("Using node %s%n",nodeUrl);// Set up sender and recipient accountsfinalStringsenderPrivateKeyString=System.getenv().getOrDefault("SENDER_PRIVATE_KEY","0".repeat(64));finalKeyPairsenderKeyPair=newKeyPair(newCryptoTypes.PrivateKey(senderPrivateKeyString));finalAddresssenderAddress=facade.network.publicKeyToAddress(senderKeyPair.getPublicKey());finalStringrecipientPrivateKeyString=System.getenv().getOrDefault("RECIPIENT_PRIVATE_KEY","1".repeat(64));finalKeyPairrecipientKeyPair=newKeyPair(newCryptoTypes.PrivateKey(recipientPrivateKeyString));finalAddressrecipientAddress=facade.network.publicKeyToAddress(recipientKeyPair.getPublicKey());System.out.printf("Sender address: %s%n",senderAddress);System.out.printf("Recipient address: %s%n%n",recipientAddress);// --- PLAIN TEXT MESSAGE ---System.out.println("==> Sending Plain Text Message");// Create a plain text messagefinalbyte[]plainMessage="Hello, NEM!".getBytes(UTF_8);System.out.printf("Plain message: %s%n",newString(plainMessage,UTF_8));// Build transfer transaction with plain messagefinalTransactionplainTransaction=facade.createTransactionFromTypedDescriptor(newTransferTransactionV2Descriptor(recipientAddress,newAmount(0),newMessageDescriptor(MessageType.PLAIN,plainMessage),List.of()),senderKeyPair.getPublicKey(),0,2*60*60);plainTransaction.setFee(newAmount(FeeCalculator.calculateTransactionFee(plainTransaction)));// Sign and announce the transactionfinalCryptoTypes.SignatureplainSignature=facade.signTransaction(senderKeyPair,plainTransaction);finalStringplainJsonPayload=NemTransactionFactory.attachSignature(plainTransaction,plainSignature);finalStringplainTransactionHash=facade.hashTransaction(plainTransaction).toString();System.out.printf("Transaction hash: %s%n",plainTransactionHash);finalHttpRequestplainRequest=HttpRequest.newBuilder(URI.create(nodeUrl+"/transaction/announce")).header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofString(plainJsonPayload)).build();HTTP_CLIENT.send(plainRequest,BodyHandlers.ofString());System.out.println("Plain message transaction announced\n");// --- RECEIVING PLAIN TEXT MESSAGE ---System.out.println("<== Receiving Plain Text Message");// Wait for confirmationfinalJsonNodeplainTxData=waitForConfirmation(plainTransactionHash,"Plain message transaction");// Decode plain message from confirmed transactionfinalbyte[]receivedPlainMessage=HexFormat.of().parseHex(plainTxData.get("transaction").get("message").get("payload").asText());System.out.printf("Received plain message: %s%n%n",newString(receivedPlainMessage,UTF_8));// --- ENCRYPTED MESSAGE ---System.out.println("==> Sending Encrypted Message");// Create a message encoder with sender's key pairfinalMessageEncodersenderMessageEncoder=newMessageEncoder(senderKeyPair);// Encrypt the message using recipient's public keyfinalbyte[]secretMessage="This is a secret message!".getBytes(UTF_8);finalMessageencryptedMessage=senderMessageEncoder.encode(recipientKeyPair.getPublicKey(),secretMessage);System.out.printf("Original message: %s%n",newString(secretMessage,UTF_8));System.out.printf("Encrypted payload: %s%n",HexFormat.of().formatHex(encryptedMessage.getMessage()));// Build transfer transaction with encrypted messagefinalTransactionencryptedTransaction=facade.createTransactionFromTypedDescriptor(newTransferTransactionV2Descriptor(recipientAddress,newAmount(0),newMessageDescriptor(MessageType.ENCRYPTED,encryptedMessage.getMessage()),List.of()),senderKeyPair.getPublicKey(),0,2*60*60);encryptedTransaction.setFee(newAmount(FeeCalculator.calculateTransactionFee(encryptedTransaction)));// Sign and announce the transactionfinalCryptoTypes.SignatureencryptedSignature=facade.signTransaction(senderKeyPair,encryptedTransaction);finalStringencryptedJsonPayload=NemTransactionFactory.attachSignature(encryptedTransaction,encryptedSignature);finalStringencryptedTransactionHash=facade.hashTransaction(encryptedTransaction).toString();System.out.printf("Transaction hash: %s%n",encryptedTransactionHash);finalHttpRequestencryptedRequest=HttpRequest.newBuilder(URI.create(nodeUrl+"/transaction/announce")).header("Content-Type","application/json").POST(HttpRequest.BodyPublishers.ofString(encryptedJsonPayload)).build();HTTP_CLIENT.send(encryptedRequest,BodyHandlers.ofString());System.out.println("Encrypted message transaction announced\n");// --- RECEIVING ENCRYPTED MESSAGE ---System.out.println("<== Receiving Encrypted Message");// Wait for confirmationfinalJsonNodeencryptedTxData=waitForConfirmation(encryptedTransactionHash,"Encrypted message transaction");// Decode encrypted message using recipient's private keyfinalMessageEncoderrecipientMessageEncoder=newMessageEncoder(recipientKeyPair);finalMessagereceivedEncryptedMessage=newMessage();receivedEncryptedMessage.setMessageType(MessageType.ENCRYPTED);receivedEncryptedMessage.setMessage(HexFormat.of().parseHex(encryptedTxData.get("transaction").get("message").get("payload").asText()));// Get sender's public key from the transactionfinalCryptoTypes.PublicKeysenderPublicKeyFromTx=newCryptoTypes.PublicKey(encryptedTxData.get("transaction").get("signer").asText());finalMessageEncoderResultresult=recipientMessageEncoder.tryDecode(senderPublicKeyFromTx,receivedEncryptedMessage);if(result.isDecoded()){System.out.printf("Recipient decrypted message: %s%n",newString((byte[])result.message(),UTF_8));}else{System.out.println("Recipient failed to decrypt message");}}}
# Set up sender and recipient accountsfacade=NemFacade('testnet')sender_private_key_string=os.getenv('SENDER_PRIVATE_KEY','0000000000000000000000000000000000000000000000000000000000000000',)sender_key_pair=NemFacade.KeyPair(PrivateKey(sender_private_key_string))sender_address=facade.network.public_key_to_address(sender_key_pair.public_key)recipient_private_key_string=os.getenv('RECIPIENT_PRIVATE_KEY','1111111111111111111111111111111111111111111111111111111111111111',)recipient_key_pair=NemFacade.KeyPair(PrivateKey(recipient_private_key_string))recipient_address=facade.network.public_key_to_address(recipient_key_pair.public_key)print(f'Sender address: {sender_address}')print(f'Recipient address: {recipient_address}\n')
// Set up sender and recipient accountsconstfacade=newNemFacade('testnet');constsenderPrivateKeyString=process.env.SENDER_PRIVATE_KEY||'0000000000000000000000000000000000000000000000000000000000000000';constsenderKeyPair=newNemFacade.KeyPair(newPrivateKey(senderPrivateKeyString));constsenderAddress=facade.network.publicKeyToAddress(senderKeyPair.publicKey);constrecipientPrivateKeyString=process.env.RECIPIENT_PRIVATE_KEY||'1111111111111111111111111111111111111111111111111111111111111111';constrecipientKeyPair=newNemFacade.KeyPair(newPrivateKey(recipientPrivateKeyString));constrecipientAddress=facade.network.publicKeyToAddress(recipientKeyPair.publicKey);console.log('Sender address:',senderAddress.toString());console.log('Recipient address:',recipientAddress.toString(),'\n');
// Set up sender and recipient accountsfinalStringsenderPrivateKeyString=System.getenv().getOrDefault("SENDER_PRIVATE_KEY","0".repeat(64));finalKeyPairsenderKeyPair=newKeyPair(newCryptoTypes.PrivateKey(senderPrivateKeyString));finalAddresssenderAddress=facade.network.publicKeyToAddress(senderKeyPair.getPublicKey());finalStringrecipientPrivateKeyString=System.getenv().getOrDefault("RECIPIENT_PRIVATE_KEY","1".repeat(64));finalKeyPairrecipientKeyPair=newKeyPair(newCryptoTypes.PrivateKey(recipientPrivateKeyString));finalAddressrecipientAddress=facade.network.publicKeyToAddress(recipientKeyPair.getPublicKey());System.out.printf("Sender address: %s%n",senderAddress);System.out.printf("Recipient address: %s%n%n",recipientAddress);
print('==> Sending Plain Text Message')# Create a plain text messageplain_message='Hello, NEM!'.encode('utf-8')print(f'Plain message: {plain_message.decode("utf-8")}')# Build transfer transaction with plain messageplain_transaction=facade.create_transaction_from_descriptor({'type':'transfer_transaction_v2','recipient_address':recipient_address,'amount':0,'message':{'message_type':'plain','message':plain_message,},},sender_key_pair.public_key,0,2*60*60)
console.log('==> Sending Plain Text Message');// Create a plain text messageconstplainMessage=newTextEncoder().encode('Hello, NEM!');console.log('Plain message:',newTextDecoder().decode(plainMessage));// Build transfer transaction with plain messageconstplainTransaction=facade.createTransactionFromTypedDescriptor(newdescriptors.TransferTransactionV2Descriptor(newAddress(recipientAddress.toString()),newmodels.Amount(0n),newdescriptors.MessageDescriptor(models.MessageType.PLAIN,plainMessage)),senderKeyPair.publicKey,0n,2*60*60);
System.out.println("==> Sending Plain Text Message");// Create a plain text messagefinalbyte[]plainMessage="Hello, NEM!".getBytes(UTF_8);System.out.printf("Plain message: %s%n",newString(plainMessage,UTF_8));// Build transfer transaction with plain messagefinalTransactionplainTransaction=facade.createTransactionFromTypedDescriptor(newTransferTransactionV2Descriptor(recipientAddress,newAmount(0),newMessageDescriptor(MessageType.PLAIN,plainMessage),List.of()),senderKeyPair.getPublicKey(),0,2*60*60);
print('==> Sending Encrypted Message')# Create a message encoder with sender's key pairsender_message_encoder=MessageEncoder(sender_key_pair)# Encrypt the message using recipient's public keysecret_message='This is a secret message!'.encode('utf-8')encrypted_message=sender_message_encoder.encode(recipient_key_pair.public_key,secret_message)print(f'Original message: {secret_message.decode("utf-8")}')encrypted_payload=hexlify(encrypted_message.message).decode('utf-8')print(f'Encrypted payload: {encrypted_payload}')# Build transfer transaction with encrypted messageencrypted_transaction=facade.create_transaction_from_descriptor({'type':'transfer_transaction_v2','recipient_address':recipient_address,'amount':0,'message':{'message_type':'encrypted','message':encrypted_message.message,},},sender_key_pair.public_key,0,2*60*60)
console.log('==> Sending Encrypted Message');// Create a message encoder with sender's key pairconstsenderMessageEncoder=newMessageEncoder(senderKeyPair);// Encrypt the message using recipient's public keyconstsecretMessage=newTextEncoder().encode('This is a secret message!');constencryptedMessage=senderMessageEncoder.encode(recipientKeyPair.publicKey,secretMessage);console.log('Original message:',newTextDecoder().decode(secretMessage));console.log('Encrypted payload:',Buffer.from(encryptedMessage.message).toString('hex'));// Build transfer transaction with encrypted messageconstencryptedTransaction=facade.createTransactionFromTypedDescriptor(newdescriptors.TransferTransactionV2Descriptor(newAddress(recipientAddress.toString()),newmodels.Amount(0n),newdescriptors.MessageDescriptor(models.MessageType.ENCRYPTED,encryptedMessage.message)),senderKeyPair.publicKey,0n,2*60*60);
System.out.println("==> Sending Encrypted Message");// Create a message encoder with sender's key pairfinalMessageEncodersenderMessageEncoder=newMessageEncoder(senderKeyPair);// Encrypt the message using recipient's public keyfinalbyte[]secretMessage="This is a secret message!".getBytes(UTF_8);finalMessageencryptedMessage=senderMessageEncoder.encode(recipientKeyPair.getPublicKey(),secretMessage);System.out.printf("Original message: %s%n",newString(secretMessage,UTF_8));System.out.printf("Encrypted payload: %s%n",HexFormat.of().formatHex(encryptedMessage.getMessage()));// Build transfer transaction with encrypted messagefinalTransactionencryptedTransaction=facade.createTransactionFromTypedDescriptor(newTransferTransactionV2Descriptor(recipientAddress,newAmount(0),newMessageDescriptor(MessageType.ENCRYPTED,encryptedMessage.getMessage()),List.of()),senderKeyPair.getPublicKey(),0,2*60*60);
print('<== Receiving Encrypted Message')# Wait for confirmationencrypted_tx_data=wait_for_confirmation(encrypted_transaction_hash,'Encrypted message transaction')# Decode encrypted message using recipient's private keyrecipient_message_encoder=MessageEncoder(recipient_key_pair)received_encrypted_message=Message()received_encrypted_message.message_type=MessageType.ENCRYPTEDreceived_encrypted_message.message=bytes.fromhex(encrypted_tx_data['transaction']['message']['payload'])# Get sender's public key from the transactionsender_public_key_from_tx=PublicKey(encrypted_tx_data['transaction']['signer'])(is_decoded,decrypted_message)=recipient_message_encoder.try_decode(sender_public_key_from_tx,received_encrypted_message)ifis_decoded:message_text=decrypted_message.decode('utf-8')print(f'Recipient decrypted message: {message_text}')else:print('Recipient failed to decrypt message')
console.log('<== Receiving Encrypted Message');// Wait for confirmationconstencryptedTxData=awaitwaitForConfirmation(encryptedTransactionHash,'Encrypted message transaction');// Decode encrypted message using recipient's private keyconstrecipientMessageEncoder=newMessageEncoder(recipientKeyPair);constreceivedEncryptedMessage=newmodels.Message();receivedEncryptedMessage.messageType=models.MessageType.ENCRYPTED;receivedEncryptedMessage.message=Buffer.from(encryptedTxData.transaction.message.payload,'hex');// Get sender's public key from the transactionconstsenderPublicKeyFromTx=newPublicKey(encryptedTxData.transaction.signer);constresult=recipientMessageEncoder.tryDecode(senderPublicKeyFromTx,receivedEncryptedMessage);if(result.isDecoded){console.log('Recipient decrypted message:',newTextDecoder().decode(result.message));}else{console.log('Recipient failed to decrypt message');}
System.out.println("<== Receiving Encrypted Message");// Wait for confirmationfinalJsonNodeencryptedTxData=waitForConfirmation(encryptedTransactionHash,"Encrypted message transaction");// Decode encrypted message using recipient's private keyfinalMessageEncoderrecipientMessageEncoder=newMessageEncoder(recipientKeyPair);finalMessagereceivedEncryptedMessage=newMessage();receivedEncryptedMessage.setMessageType(MessageType.ENCRYPTED);receivedEncryptedMessage.setMessage(HexFormat.of().parseHex(encryptedTxData.get("transaction").get("message").get("payload").asText()));// Get sender's public key from the transactionfinalCryptoTypes.PublicKeysenderPublicKeyFromTx=newCryptoTypes.PublicKey(encryptedTxData.get("transaction").get("signer").asText());finalMessageEncoderResultresult=recipientMessageEncoder.tryDecode(senderPublicKeyFromTx,receivedEncryptedMessage);if(result.isDecoded()){System.out.printf("Recipient decrypted message: %s%n",newString((byte[])result.message(),UTF_8));}else{System.out.println("Recipient failed to decrypt message");}