-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugin.js
176 lines (152 loc) · 4.87 KB
/
plugin.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
174
175
'use strict'
const express = require('express')
const Web3 = require('web3')
const Machinomy = require('machinomy').default
const Payment = require('machinomy/lib/payment').default
const bodyParser = require('body-parser')
const promisify = require('util').promisify
const fetch = require('node-fetch')
const debug = require('debug')('ilp-plugin-ethereum-paychan')
const DEFAULT_PROVIDER_URI = 'http://localhost:8545'
class PluginEthereumPaychan {
constructor ({ port, server, provider, account, db, minimumChannelAmount }) {
this.port = port
this.server = server
this.account = account || ''
this.peerAccount = ''
this.db = db || 'machinomy_db'
this.minimumChannelAmount = (typeof minimumChannelAmount === 'number' ? minimumChannelAmount : 100)
if (typeof provider === 'string') {
this.provider = new Web3.providers.HttpProvider(provider)
} else if (provider) {
this.provider = provider
} else {
this.provider = new Web3.providers.HttpProvider(DEFAULT_PROVIDER_URI)
}
this.web3 = new Web3(this.provider)
this.machinomy = null
this.moneyHandler = () => Promise.resolve()
this.dataHandler = () => Promise.resolve(Buffer.alloc(0))
}
async connect () {
debug('connecting')
if (!this.account) {
const accounts = await promisify(web3.eth.getAccounts)()
if (accounts.length === 0) {
throw new Error('Provider has no accounts registered')
}
this.account = accounts[0]
}
this.machinomy = new Machinomy(this.account, this.web3, {
engine: 'nedb',
databaseFile: this.db,
minimumChannelAmount: this.minimumChannelAmount
})
if (this.server) {
debug('attempting to connect to peer')
const result = await fetch(this.server)
if (!result.ok) {
throw new Error('Unable to reach peer server')
}
const body = await result.json()
this.peerAccount = body.account
debug('connected to peer')
}
// Make sure there is an open channel to the receiver so that we don't have to wait when we want to send payments
// Based on suggestion in https://github.com/machinomy/machinomy/issues/123#issuecomment-357537398
if (this.server) {
await this.machinomy.buy({
price: 0,
gateway: this.server + '/money',
receiver: this.peerAccount,
meta: ''
})
}
if (this.port) {
// TODO switch to koa or plain http(s) server
const app = express()
app.get('/', (req, res) => {
debug('got connection from:', req.ip)
res.send({
account: this.account
})
res.status(200)
res.end()
})
app.post('/money', bodyParser.json(), async (req, res, next) => {
const payment = new Payment(req.body)
debug('got payment:', payment)
const token = await this.machinomy.acceptPayment(payment)
if (payment.price > 0) {
await this.moneyHandler('' + payment.price)
}
res.header('Paywall-Token', token)
res.status(200)
res.end()
})
app.post('/data', bodyParser.raw(), async (req, res, next) => {
debug('got data:', req.body.toString('hex'))
const response = await this.dataHandler(req.body)
res.send(response)
res.end()
})
this.listener = app.listen(this.port)
debug('listening on port:', this.port)
}
debug('connected')
}
async disconnect () {
debug('disconnect')
// Stop accepting data and money
if (this.listener) {
this.listener.close()
}
// Close existing channels
for (let channel of await this.machinomy.channels()) {
try {
await this.machinomy.close(channel.channelId)
debug('closed channel:', channel.channelId)
} catch (err) {
console.error('error closing channel:', channel.channelId, err)
}
}
}
async sendData (data) {
debug('sending data:', data.toString('hex'))
const result = await fetch(this.server + '/data', {
method: 'POST',
body: data,
headers: {
'Content-Type': 'application/octet-stream'
}
})
const resultBuffer = await result.buffer()
debug('got response:', resultBuffer.toString('hex'))
return resultBuffer
}
async sendMoney (amount) {
debug('sending money:', amount)
await this.machinomy.buy({
price: Number(amount),
gateway: this.server + '/money',
receiver: this.peerAccount,
meta: ''
})
return
}
registerDataHandler (handler) {
this.dataHandler = handler
}
deregisterDataHandler () {
this.dataHandler = () => Promise.resolve(Buffer.alloc(0))
}
registerMoneyHandler (handler) {
this.moneyHandler = handler
}
deregisterDataHandler () {
this.moneyHandler = () => Promise.resolve()
}
}
PluginEthereumPaychan.version = 2
// TODO use es6 modules style export?
module.exports = PluginEthereumPaychan