-
Notifications
You must be signed in to change notification settings - Fork 7
/
nimiq_watch.php
263 lines (219 loc) · 9.29 KB
/
nimiq_watch.php
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
<?php
include_once( dirname( __FILE__ ) . DIRECTORY_SEPARATOR . 'interface.php' );
class WC_Gateway_Nimiq_Service_Nimiqwatch implements WC_Gateway_Nimiq_Validation_Service_Interface {
// Constants
const API_TX_PER_PAGE = 25;
/**
* Initializes the validation service
* @param {WC_Gateway_Nimiq} $gateway - A WC_Gateway_Nimiq class instance
* @return {void}
*/
public function __construct( $gateway ) {
$this->transaction = null;
$this->payment_state = null;
$this->transactions = [];
$this->head_height = null;
$this->page = 0;
$this->last_api_call_time = null;
$this->api_domain = $gateway->get_option( 'network' ) === 'main'
? 'https://api.nimiq.watch'
: 'https://test-api.nimiq.watch';
}
/**
* Retrieves the current blockchain head height
* @return {number|WP_Error}
*/
public function blockchain_height() {
if ( !empty( $this->head_height ) ) {
return $this->head_height;
}
$api_response = wp_remote_get( $this->api_domain . '/latest/1' );
if ( is_wp_error( $api_response ) ) {
return $api_response;
}
$latest_block = json_decode( $api_response[ 'body' ] );
if ( $latest_block->error ) {
return new WP_Error( 'service', $latest_block->error );
}
if ( empty( $latest_block ) ) {
return new WP_Error( 'service', sprintf( __( 'Could not get the current blockchain height from %s.', 'wc-gateway-nimiq' ), 'NIMIQ.WATCH') );
}
$this->head_height = $latest_block[ 0 ]->height;
return $this->head_height;
}
/**
* Loads a transaction from the service
* @param {string} $transaction_hash - Transaction hash as HEX string
* @param {WP_Order} $order
* @param {WC_Gateway_Nimiq} $gateway
* @return {'NOT_FOUND'|'PAID'|'OVERPAID'|'UNDERPAID'|WP_Error}
*/
public function load_transaction( $transaction_hash, $order, $gateway ) {
// Reset loaded transaction
$this->transaction = null;
$this->payment_state = null;
$recipient_address = null;
if ( !empty( $transaction_hash ) ) {
if ( !ctype_xdigit( $transaction_hash ) ) {
return new WP_Error('service', __( 'Invalid transaction hash.', 'wc-gateway-nimiq' ) );
}
// Convert HEX hash into base64
$transaction_hash = urlencode( base64_encode( pack( 'H*', $transaction_hash ) ) );
$api_response = wp_remote_get( $this->api_domain . '/transaction/' . $transaction_hash );
if ( is_wp_error( $api_response ) ) {
return $api_response;
}
$this->transaction = json_decode( $api_response[ 'body' ] );
return $this->transaction_found() ? 'PAID' : 'NOT_FOUND';
}
$recipient_address = Order_Utils::get_order_recipient_address( $order, $gateway );
// TODO: NIM Address validation
// if ( !AddressValidator::isValid( $recipient_address ) ) {
// return new WP_Error('service', __( 'Invalid merchant address.', 'wc-gateway-nimiq' ) );
// }
$head_height = $this->blockchain_height();
if ( is_wp_error( $head_height ) ) {
return $head_height;
}
// Use cached results, if any
$response = $this->transactions;
$page = $this->page;
while ( !$this->transaction ) {
$transaction = $this->find_transaction( $recipient_address, $order, $response, $gateway );
if ( $transaction && $this->payment_state ) {
$this->transaction = $transaction;
// Store tx hash in order
$order->update_meta_data( 'transaction_hash', $transaction->hash );
$order->update_meta_data( 'customer_nim_address', $transaction->sender_address );
$order->update_meta_data( 'nc_payment_state', $this->payment_state );
$order->save();
return $this->payment_state;
}
if ( $this->payment_state === 'UNDERPAID' ) return $this->payment_state;
// Stop when no more transactions are available
// ($page is set to -1 below, when a paged API call returns less than API_TX_PER_PAGE transactions)
if ( $page < 0 ) {
return 'NOT_FOUND';
}
// Stop when earliest transaction is earlier than the order date
$order_date = $order->get_data()[ 'date_created' ]->getTimestamp();
if ( end( $response ) && ( empty( end( $response )->timestamp ) || end( $response )->timestamp < $order_date ) ) {
return 'NOT_FOUND';
}
// NIMIQ.WATCH API has a rate-limit of 10 requests/second, so we need to sleep for 100ms between requests
if ( $this->last_api_call_time ) {
$diff = $this->get_milliseconds() - $this->last_api_call_time;
$wait = max( 0, 100 - $diff );
usleep( $wait * 1e3 );
}
$page += 1;
$this->last_api_call_time = $this->get_milliseconds();
$api_response = wp_remote_get( $this->get_url_transactions_by_address( $recipient_address, $page ) );
if ( is_wp_error( $api_response ) ) {
return $api_response;
}
$response = array_reverse( json_decode( $api_response[ 'body' ] ) );
// Check number of returned transactions
if ( count( $response ) < self::API_TX_PER_PAGE ) {
$page = -1; // Signal that all transactions have been fetched
}
// Cache API results
$this->add_transactions( $response );
$this->page = $page;
}
}
/**
* Returns if transaction was found or not
* @return {boolean}
*/
public function transaction_found() {
return !!$this->transaction;
}
/**
* Returns any error that the service returned
* @return {string|false}
*/
public function error() {
return $this->transaction->error ?: false;
}
/**
* Returns the userfriendly address of the transaction sender
* @return {string}
*/
public function sender_address() {
return $this->transaction->sender_address;
}
/**
* Returns the userfriendly address of the transaction recipient
* @return {string}
*/
public function recipient_address() {
return $this->transaction->receiver_address;
}
/**
* Returns the value of the transaction in the smallest unit
* @return {string}
*/
public function value() {
return strval( $this->transaction->value );
}
/**
* Returns the data (message) of the transaction in plain text
* @return {string}
*/
public function message() {
$extraData = base64_decode( $this->transaction->data );
return mb_convert_encoding( $extraData, 'UTF-8' );
}
/**
* Returns the height of the block containing the transaction
* @return {number}
*/
public function block_height() {
return $this->transaction->block_height;
}
/**
* Returns the confirmations of the transaction
* @return {number}
*/
public function confirmations() {
return $this->blockchain_height() + 1 - $this->block_height();
}
private function get_milliseconds() {
return ceil( microtime(true) * 1e3 );
}
private function find_transaction( $recipient_address, $order, $transactions, $gateway ) {
$order_date = $order->get_data()[ 'date_created' ]->getTimestamp();
foreach ( $transactions as $tx ) {
// Check that tx is not too old
if (!empty( $tx->timestamp ) && $tx->timestamp < $order_date) return null;
if ( $tx->receiver_address === $recipient_address ) {
// If tx has a message, check that it matches
$extraData = base64_decode( $tx->data );
$message = mb_convert_encoding( $extraData, 'UTF-8' );
if ( !empty( $message ) ) {
// Look for the last pair of round brackets in the tx message
preg_match_all( '/.*\((.*?)\)/', $message, $matches, PREG_SET_ORDER );
$tx_order_key = end( $matches )[1];
if ( $tx_order_key !== $gateway->get_short_order_key( $order->get_order_key() ) ) {
continue;
}
}
$comparison = Crypto_Manager::unit_compare( $tx->value, Order_Utils::get_order_total_crypto( $order ) );
$this->payment_state = Order_Utils::get_payment_state( $comparison );
if ( $comparison >= 0 ) return $tx;
}
}
return null;
}
private function add_transactions( $transactions ) {
foreach ( $transactions as $tx ) {
$this->transactions[ $tx->hash ] = $tx;
}
}
private function get_url_transactions_by_address( string $address, int $page = 1 ) {
$path = '/account-transactions/' . $address . '/' . self::API_TX_PER_PAGE . '/' . ( $page - 1 ) * self::API_TX_PER_PAGE;
return $this->api_domain . $path;
}
}
$services['nim'] = new WC_Gateway_Nimiq_Service_Nimiqwatch( $gateway );