Last active
July 10, 2018 10:49
-
-
Save rohitkhatri/04bb90c531385d8825c5243773d6a269 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { TransactionHandler } = require('sawtooth-sdk/processor/handler'); | |
const { InvalidTransaction } = require('sawtooth-sdk/processor/exceptions'); | |
const { TextEncoder, TextDecoder } = require('text-encoding/lib/encoding'); | |
const crypto = require('crypto'); | |
const encoder = new TextEncoder('utf8'); | |
const decoder = new TextDecoder('utf8'); | |
const TP_FAMILY = 'grocery'; | |
const TP_NAMESPACE = _hash(TP_FAMILY).substring(0, 6); | |
class AircraftHandler extends TransactionHandler { | |
constructor() { | |
super(TP_FAMILY, ['1.0'], [TP_NAMESPACE]); | |
this.timeout = 500; | |
} | |
apply(request, context) { | |
console.log('Transaction Processor Called!'); | |
this._context = context; | |
this._request = request; | |
const actions = ['createOrder']; | |
try { | |
let payload = JSON.parse(decoder.decode(request.payload)); | |
let action = payload.action | |
if(!action || !actions.includes(action)) { | |
throw new InvalidTransaction(`Upsupported action "${action}"!`); | |
} | |
try { | |
return this[action](payload.data); | |
} catch(e) { | |
console.log(e); | |
} | |
} catch(e) { | |
throw new InvalidTransaction('Pass a valid json string.'); | |
} | |
} | |
createOrder(payload) { | |
console.log('Creating order!'); | |
let data = { | |
id: payload.id, | |
status: payload.status, | |
created_at: Math.floor((new Date()).getTime() / 1000) | |
}; | |
return this._setEntry(this._makeAddress(payload.id), data); | |
} | |
_setEntry(address, payload) { | |
let dataBytes = encoder.encode(JSON.stringify(payload)); | |
let entries = { | |
[address]: dataBytes | |
} | |
return this._context.setState(entries); | |
} | |
_makeAddress(id) { | |
return TP_NAMESPACE + crypto.createHash('sha512').update(id).digest('hex').toLowerCase().substr(0,64); | |
} | |
} | |
const transactionProcessor = new TransactionProcessor('tcp://validator:4004'); | |
transactionProcessor.addHandler(new AircraftHandler()); | |
transactionProcessor.start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment