lbry.go/address/validate.go

70 lines
2 KiB
Go
Raw Normal View History

2017-09-12 18:02:30 +02:00
package address
import (
"github.com/lbryio/lbry.go/extras/errors"
2018-02-15 20:51:51 +01:00
"github.com/lbryio/lbryschema.go/address/base58"
2017-09-12 18:02:30 +02:00
)
2018-02-15 20:51:51 +01:00
const lbrycrdMainPubkeyPrefix = byte(85)
const lbrycrdMainScriptPrefix = byte(122)
2018-02-15 20:51:51 +01:00
const lbrycrdTestnetPubkeyPrefix = byte(111)
const lbrycrdTestnetScriptPrefix = byte(196)
2018-02-15 20:51:51 +01:00
const lbrycrdRegtestPubkeyPrefix = byte(111)
const lbrycrdRegtestScriptPrefix = byte(196)
2018-02-15 20:51:51 +01:00
const prefixLength = 1
const pubkeyLength = 20
const checksumLength = 4
const addressLength = prefixLength + pubkeyLength + checksumLength
2018-02-15 20:51:51 +01:00
const lbrycrdMain = "lbrycrd_main"
const lbrycrdTestnet = "lbrycrd_testnet"
const lbrycrdRegtest = "lbrycrd_regtest"
2017-09-12 18:02:30 +02:00
var addressPrefixes = map[string][2]byte{
lbrycrdMain: [2]byte{lbrycrdMainPubkeyPrefix, lbrycrdMainScriptPrefix},
lbrycrdTestnet: [2]byte{lbrycrdTestnetPubkeyPrefix, lbrycrdTestnetScriptPrefix},
lbrycrdRegtest: [2]byte{lbrycrdRegtestPubkeyPrefix, lbrycrdRegtestScriptPrefix},
}
2018-02-15 20:51:51 +01:00
func PrefixIsValid(address [addressLength]byte, blockchainName string) bool {
2017-09-12 18:02:30 +02:00
prefix := address[0]
2018-02-15 20:51:51 +01:00
for _, addrPrefix := range addressPrefixes[blockchainName] {
if addrPrefix == prefix {
2017-09-12 18:02:30 +02:00
return true
}
}
return false
}
2018-02-15 20:51:51 +01:00
func PubKeyIsValid(address [addressLength]byte) bool {
pubkey := address[prefixLength : pubkeyLength+prefixLength]
2017-09-12 18:02:30 +02:00
// TODO: validate this for real
2018-02-15 20:51:51 +01:00
if len(pubkey) != pubkeyLength {
2017-09-12 18:02:30 +02:00
return false
}
return true
}
2018-02-15 20:51:51 +01:00
func ChecksumIsValid(address [addressLength]byte) bool {
return base58.VerifyBase58Checksum(address[:])
2017-09-12 18:02:30 +02:00
}
2018-02-15 20:51:51 +01:00
func ValidateAddress(address [addressLength]byte, blockchainName string) ([addressLength]byte, error) {
if blockchainName != lbrycrdMain && blockchainName != lbrycrdTestnet && blockchainName != lbrycrdRegtest {
return address, errors.Err("invalid blockchain name")
}
if !PrefixIsValid(address, blockchainName) {
return address, errors.Err("invalid prefix")
2017-09-12 18:02:30 +02:00
}
if !PubKeyIsValid(address) {
return address, errors.Err("invalid pubkey")
2017-09-12 18:02:30 +02:00
}
2018-02-15 20:51:51 +01:00
if !ChecksumIsValid(address) {
return address, errors.Err("invalid address checksum")
2017-09-12 18:02:30 +02:00
}
return address, nil
}