-
Notifications
You must be signed in to change notification settings - Fork 62
/
transaction.js
62 lines (51 loc) · 1.31 KB
/
transaction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var crypto = require('crypto');
var ByteBuffer = require('bytebuffer');
var _ = require('lodash');
function Transaction(data) {
this.data = _.assign({
amount: 0,
timestamp: Math.floor(Date.now() / 1000),
recipient: '',
sender: ''
}, data);
if (!this.data.hash) {
this.data.hash = this.calculateHash();
}
}
Transaction.prototype.getData = function() {
return this.data;
}
Transaction.prototype.getSize = function() {
return this.size;
}
Transaction.prototype.getHash = function() {
return this.data.hash;
}
Transaction.prototype.getAmount = function() {
return this.data.amount;
}
Transaction.prototype.getTimestamp = function() {
return this.data.timestamp;
}
Transaction.prototype.getRecipient = function() {
return this.data.recipient;
}
Transaction.prototype.getSender = function() {
return this.data.sender;
}
Transaction.prototype.getBytes = function() {
var buf = new ByteBuffer();
var d = this.data;
buf.writeLong(d.amount);
buf.writeInt(d.timestamp);
buf.writeIString(d.recipient);
buf.writeIString(d.sender);
buf.flip();
return buf.toBuffer();
}
Transaction.prototype.calculateHash = function() {
var bytes = this.getBytes();
this.size = bytes.length;
return crypto.createHash('sha256').update(bytes).digest().toString('hex');
}
module.exports = Transaction;