forked from agektmr/payment-request-show
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
173 lines (146 loc) · 4.8 KB
/
app.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
'use strict';
const XrpEscrowPlugin = require('ilp-plugin-xrp-escrow');
const IlpPacket = require('ilp-packet')
const crypto = require('crypto');
const express = require('express');
function sha256(preimage) {
return crypto.createHash('sha256').update(preimage).digest()
}
function base64url(buf) {
return buf.toString('base64')
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
function base64url_decode(string) {
return new Buffer(
string.replace(/\-/g, '+').replace(/\_/g, '/'), 'base64');
}
const plugins = [];
registerPlugin(new XrpEscrowPlugin({
secret: 'sndb5JDdyWiHZia9zv44zSr2itRy1',
account: 'rGtqDAJNTDMLaNNfq1RVYgPT8onFMj19Aj',
server: 'wss://s.altnet.rippletest.net:51233',
prefix: 'test.crypto.xrp.',
}), 0.2);
plugins.push({
ledgerPrefix: 'test.stripe.usd.',
account: 'test.stripe.usd.merchant-1234',
currencyCode: 'USD',
currencyScale: 2,
exchangeRate: 1,
});
/**
* Register a plugin with the server including the rate of exchange to use.
*
* Will connect the plugin and get info about the ledger and account
*
* @param {*} plugin An LPI plugin configured for a receiving account
* @param {*} exchangeRate The exchange rates this receiving account uses vs the
*/
function registerPlugin(plugin, exchangeRate) {
plugin.connect().then(() => {
const ledgerInfo = plugin.getInfo();
const account = plugin.getAccount();
console.log(`Connected to ledger: ${ledgerInfo.prefix}`);
console.log(` - Account: ${account}`);
console.log(` - Currency: ${ledgerInfo.currencyCode}`);
console.log(` - CurrencyScale: ${ledgerInfo.currencyScale}`);
console.log(` - ExchangeRate: ${exchangeRate}`);
registerPaymentHandler(plugin);
plugins.push({
ledgerPrefix: ledgerInfo.prefix,
account: account,
currencyCode: ledgerInfo.currencyCode,
currencyScale: ledgerInfo.currencyScale,
exchangeRate: exchangeRate,
// secret: crypto.randomBytes(32),
plugin: plugin,
});
});
}
function registerPaymentHandler(plugin) {
plugin.on('incoming_prepare', function(transfer) {
const condition = transfer.executionCondition;
const transferId = transfer.id;
const ilpPacket = base64url_decode(transfer.ilp);
const fulfillment = sha256(ilpPacket);
const testCondition = base64url(sha256(fulfillment));
console.log(`Incoming payment for tx: ${transferId}`);
if(condition !== testCondition) {
console.log(` - Unfulfillable condition: ${condition}`);
plugin.rejectIncomingTransfer(transferId, {
code: 'F05',
name: 'Wrong Condition',
message: `Unable to fulfill the condition:` +
` ${base64url(condition)}`,
triggered_by: plugin.getAccount(),
triggered_at: new Date().toISOString(),
forwarded_by: [],
additional_info: {},
});
} else {
// The ledger will check if the fulfillment is correct and
// if it was submitted before the transfer's rollback timeout
plugin.fulfillCondition(transferId, fulfillment).then(() => {
console.log(`Payment complete (fulfilled)`);
}).catch(() => {
console.log(`Error fulfilling the transfer`);
});
}
});
}
const app = express();
app.get('/demo/ilp-addresses.json', (req, res) => {
let pluginData = [];
plugins.forEach(function(plugin) {
pluginData.push({
address: plugin.account,
currencyCode: plugin.currencyCode,
currencyScale: plugin.currencyScale,
exchangeRate: plugin.exchangeRate,
});
});
res.json(pluginData);
});
/**
* Construct payment request data for this receiving address
*/
app.post('/demo/create-payment-request/', express.json(), (req, res) => {
const address = req.body.address;
const amount = req.body.amount;
// Find receiving account
const plugin = plugins.find(
(p) => address.startsWith(p.account));
if(!plugin) {
res.status(400).send({
error: 'Unknown address.',
});
} else {
const convertedAmount = amount / plugin.exchangeRate;
const ledgerAmount = convertedAmount * Math.pow(10, plugin.currencyScale);
const packet = IlpPacket.serializeIlpPayment({
amount: `${ledgerAmount}`,
account: address,
});
const fulfillment = sha256(packet);
const condition = sha256(fulfillment);
res.json({
address: address,
amount: `${ledgerAmount}`,
packet: base64url(packet),
condition: base64url(condition),
});
}
});
app.use((err, req, res, next) => {
console.error(err.stack);
});
app.get('*', express.static('app'));
/**
* Starts the server.
*/
if (module === require.main) {
let server = app.listen(process.env.PORT || 8081, function() {
console.log('Server listening on port %s', server.address().port);
});
}
module.exports = app;