forked from ognus/wallet-address-validator
-
Notifications
You must be signed in to change notification settings - Fork 104
/
monero_validator.js
64 lines (55 loc) · 1.88 KB
/
monero_validator.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
var cryptoUtils = require('./crypto/utils')
var cnBase58 = require('./crypto/cnBase58')
var DEFAULT_NETWORK_TYPE = 'prod'
var addressRegTest = new RegExp(
'^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{95}$'
)
var integratedAddressRegTest = new RegExp(
'^[123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz]{106}$'
)
function validateNetwork(decoded, currency, networkType, addressType) {
var network = currency.addressTypes
if (addressType == 'integrated') {
network = currency.iAddressTypes
}
var at = parseInt(decoded.substr(0, 2), 16).toString()
switch (networkType) {
case 'prod':
return network.prod.indexOf(at) >= 0
case 'testnet':
return network.testnet.indexOf(at) >= 0
case 'stagenet':
return network.stagenet.indexOf(at) >= 0
case 'both':
return network.prod.indexOf(at) >= 0 || network.testnet.indexOf(at) >= 0 || network.stagenet.indexOf(at) >= 0
default:
return false
}
}
function hextobin(hex) {
if (hex.length % 2 !== 0) return null
var res = new Uint8Array(hex.length / 2)
for (var i = 0; i < hex.length / 2; ++i) {
res[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)
}
return res
}
module.exports = {
isValidAddress: function(address, currency, opts = {}) {
const { networkType = DEFAULT_NETWORK_TYPE} = opts;
var addressType = 'standard'
if (!addressRegTest.test(address)) {
if (integratedAddressRegTest.test(address)) {
addressType = 'integrated'
} else {
return false
}
}
var decodedAddrStr = cnBase58.decode(address)
if (!decodedAddrStr) return false
if (!validateNetwork(decodedAddrStr, currency, networkType, addressType)) return false
var addrChecksum = decodedAddrStr.slice(-8)
var hashChecksum = cryptoUtils.keccak256Checksum(hextobin(decodedAddrStr.slice(0, -8)))
return addrChecksum === hashChecksum
}
}