Created
November 7, 2017 20:14
-
-
Save ambethia/20f28b5e4af81a130013eaf44b3c7ea0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'openssl' | |
module Neo | |
class Key | |
ADDRESS_VERSION = '17' | |
PUSHBYTES33 = '21' | |
CHECKSIG = 'ac' | |
WIF_PREFIX = '80' # MainNet | |
WIF_SUFFIX = '01' # Compressed | |
def initialize | |
@key = OpenSSL::PKey::EC.new('prime256v1').generate_key | |
end | |
def private_hex | |
@key.private_key.to_s(16).downcase | |
end | |
def public_key_encoded | |
@key.public_key.to_bn(:compressed).to_s(16).downcase | |
end | |
def script | |
PUSHBYTES33 + public_key_encoded + CHECKSIG | |
end | |
def script_hash | |
bytes = [script].pack("H*") | |
sha256 = Digest::SHA256.digest(bytes) | |
Digest::RMD160.hexdigest(sha256) | |
end | |
def address | |
Base58.encode(with_checksum(ADDRESS_VERSION + script_hash).to_i(16)) | |
end | |
def wif | |
Base58.encode(with_checksum(WIF_PREFIX + private_hex + WIF_SUFFIX).to_i(16)) | |
end | |
def with_checksum(hex) | |
bytes = [hex].pack("H*") | |
hash1 = Digest::SHA256.digest(bytes) | |
hash2 = Digest::SHA256.hexdigest(hash1) | |
hex + hash2.slice(0, 8) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment