设备和平台模拟

This commit is contained in:
myh 2024-06-05 16:07:24 +08:00
parent a1c481cef4
commit a2161b8c46
5 changed files with 4873 additions and 0 deletions

2
simulations/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules
config*.json

74
simulations/device.js Normal file
View File

@ -0,0 +1,74 @@
const request = require('request');
const { hashPersonalMessage, ecsign, ecrecover, toRpcSig, fromRpcSig, keccak256, addHexPrefix, sha3 } = require('ethereumjs-util');
const { default: MerkleTree } = require('merkle-tree-solidity');
const args = process.argv.slice(2);
const [configPath] = args;
// Configuration file downloaded after registering device
const deviceConfig = require(configPath);
const hashMessageEth = message => hashPersonalMessage(Buffer.from(message));
const signMessageEth = (message, privateKey) => {
let messageHash = hashMessageEth(message);
//console.log('Message hash: ' + messageHash.toString('hex'));
let { v, r, s } = ecsign(messageHash, privateKey);
let rpcSignature = toRpcSig(v, r, s);
//console.log('Message signature: ' + rpcSignature);
return rpcSignature;
}
const validateSignatureEth = (messageHash, signature, publicKey, address) => {
signature = fromRpcSig(signature);
let recoveredPublicKey = ecrecover(messageHash, signature.v, signature.r, signature.s);
let recoveredPublicKeyHex = recoveredPublicKey.toString('hex');
let recoveredAddress = addHexPrefix(keccak256(recoveredPublicKey).toString('hex').substring(64 - 40));
//console.log('Recovered public key: ' + recoveredPublicKeyHex);
//console.log('Recovered address: ' + recoveredAddress);
if (recoveredPublicKeyHex === publicKey && recoveredAddress === address) return true;
return false;
}
// Gather data and sign
const privateKey = Buffer.from(deviceConfig.privateKey, 'hex');
let message = 'test';
let signature = signMessageEth(message, privateKey);
// Validate signature
if (!validateSignatureEth(hashMessageEth(message), signature, deviceConfig.publicKey, deviceConfig.address)) {
process.exit();
}
// Construct Merkle tree
const metadataHashes = deviceConfig.metadata.map(el => sha3(el));
const merkleTree = new MerkleTree(metadataHashes);
// Index of metadata element to send
const elementToSend = 0;
// Generate proof
let proof = merkleTree.getProof(metadataHashes[elementToSend]);
proof = proof.map(el => addHexPrefix(el.toString('hex')));
// Build payload
let payload = {
deviceId: deviceConfig.deviceId,
message,
signature: signature,
metadata: deviceConfig.metadata[elementToSend],
proof,
firmware: deviceConfig.firmware,
curve: deviceConfig.curve
}
// Send to platform
const platformEndpoint = 'http://localhost:1337/receive'
request.post({ url: platformEndpoint, json: payload }, function (error, response, body) {
if (!error) {
console.log(body)
} else {
console.log(error);
}
})

4737
simulations/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

11
simulations/package.json Normal file
View File

@ -0,0 +1,11 @@
{
"name": "simulations",
"version": "0.1.0",
"dependencies": {
"ethereumjs-util": "5.2.0",
"express": "4.16.3",
"merkle-tree-solidity": "1.0.8",
"request": "2.88.0",
"web3": "0.20.6"
}
}

49
simulations/platform.js Normal file
View File

@ -0,0 +1,49 @@
const express = require('express');
const app = express();
const Web3 = require('web3');
const { hashPersonalMessage, addHexPrefix, sha3 } = require('ethereumjs-util');
const hashMessageHex = message => addHexPrefix(hashPersonalMessage(Buffer.from(message)).toString('hex'));
app.use(express.json());
const DeviceManagerArtifact = require('../build/contracts/DeviceManager.json');
let latestNetwork = DeviceManagerArtifact.networks[Object.keys(DeviceManagerArtifact.networks).reduce((res, curr) => curr > res ? curr : res)];
// Connect to local node
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
web3.eth.defaultAccount = web3.eth.accounts[0];
// Instance using ABI and contract address
const deviceManager = web3.eth.contract(DeviceManagerArtifact.abi).at(latestNetwork.address);
// Receive payload and validate on blockchain
app.post('/receive', function (req, res) {
console.log('received payload: ' + JSON.stringify(req.body));
// Validate message
const { deviceId, message, signature } = req.body;
let validMessage = deviceManager.isValidEthMessage(deviceId, hashMessageHex(message), signature);
console.log('valid message: ' + validMessage);
// Validate metadata
const { metadata, proof } = req.body;
let metadataHash = addHexPrefix(sha3(metadata).toString('hex'));
let validMetadata = deviceManager.isValidMetadataMember(deviceId, proof, metadataHash);
console.log('valid metadata: ' + validMetadata);
// Validate firmware
const { firmware } = req.body;
let firmwareHash = addHexPrefix(sha3(firmware).toString('hex'));
let validFirmware = deviceManager.isValidFirmwareHash(deviceId, firmwareHash);
console.log('valid firmware: ' + validFirmware);
// Respond back with status
res.send({
validMessage,
validMetadata,
validFirmware
});
})
app.listen(1337, () => console.log('Platform simulation listening on port 1337'));