LegitStack

LegitStack

Verifying Blockchain crypto signature Elixir/erlang

There are a few questions about this but not specific to blockchain. I have a Ravencoin wallet (bitcoin fork) written in python that I want to talk to my Elixir server. The wallet has a pubkey and an address (derived from the pubkey) and the ability to sign things. The server needs the ability to verify the signature.

I’ve tried to consult these resources but am unable to get it to work
Right way to use :crypto.verify(...)
GitHub - ntrepid8/ex_crypto: Wrapper around the Erlang crypto module for Elixir. · GitHub
Web3x.Wallet — web3x v0.6.3 eth
https://blog.lelonek.me/how-to-calculate-bitcoin-address-in-elixir-68939af4f0e9
Curvy — Curvy v0.3.1

Has anyone had to do this specifically with blockchain signatures?

:crypto.verify(
    :ecdsa,
    :sha256,
    "message",
    signature,
    [public_key, :secp256k1]
)

First 10 of 16 Posts Switch mode

hst337

hst337

Can you provide any additional information?
For example, the signature and the key.

Because, the call looks correct, so the problem is with padding or something like this

LegitStack

LegitStack OP

Yes, sorry, I put additional detail here:

hst337

hst337

  1. Base.decode64! the signature
  2. Base.decode16! the public key
  3. Find the right encoding options
hst337

hst337

It would help if you could share the source of this python library

LegitStack

LegitStack OP

iex(4)> :crypto.verify(:ecdsa, :sha256, "message", Base.decode64!("IFdGdzqI9fJJDbTASGbamHFQ7hlIT07jLALhYRhMrRY3QvKJuL2q8ojtwKsubj0EVtWJtlM8MbgmpvIaKwpjc04="), ["034e328758d422ce5c3a17c15528df1216ef0eaf845147876eea82d139755129a0", :secp256k1])
false

iex(5)> :crypto.verify(:ecdsa, :sha256, "message", Base.decode64!("IFdGdzqI9fJJDbTASGbamHFQ7hlIT07jLALhYRhMrRY3QvKJuL2q8ojtwKsubj0EVtWJtlM8MbgmpvIaKwpjc04="), [Base.decode64!("034e328758d422ce5c3a17c15528df1216ef0eaf845147876eea82d139755129a0"), :secp256k1])
** (ArgumentError) incorrect padding
    (elixir 1.13.4) lib/base.ex:1110: Base.do_decode64/2

iex(5)> :crypto.verify(:ecdsa, :sha256, "message", Base.decode64!("IFdGdzqI9fJJDbTASGbamHFQ7hlIT07jLALhYRhMrRY3QvKJuL2q8ojtwKsubj0EVtWJtlM8MbgmpvIaKwpjc04="), ["RMK1yBucDCJXjppB7bkZ4dMoZqr3ZKgztN", :secp256k1])
false

iex(6)> :crypto.verify(:ecdsa, :sha256, "message", Base.decode64!("IFdGdzqI9fJJDbTASGbamHFQ7hlIT07jLALhYRhMrRY3QvKJuL2q8ojtwKsubj0EVtWJtlM8MbgmpvIaKwpjc04="), [Base.decode16!("034e328758d422ce5c3a17c15528df1216ef0eaf845147876eea82d139755129a0"), :secp256k1])
** (ArgumentError) non-alphabet digit found: "e" (byte 101)
    (elixir 1.13.4) lib/base.ex:881: Base.dec16_upper/1
    (elixir 1.13.4) lib/base.ex:898: Base."-do_decode16/2-lbc$^0/2-1-"/2
    (elixir 1.13.4) lib/base.ex:893: Base.do_decode16/2

It seems the public_key isn’t hex? How does base58 encoding play into this?

LegitStack

LegitStack OP

Here’s the entire wallet object:

import os
from satori import config
from satori.lib.apis.ravencoin import Ravencoin
from satori.lib.apis.disk import WalletApi
from satori.lib.wallet import sign
import ravencoin.base58
from ravencoin.wallet import P2PKHRavencoinAddress, CRavencoinSecret
import mnemonic

class Wallet():
    
    def __init__(self):
        self._entropy = None
        self._privateKeyObj = None
        self._addressObj = None
        self.publicKey = None
        self.privateKey = None
        self.words = None
        self.address = None
        self.scripthash = None
        self.stats = None
        self.banner = None
        self.rvn = None
        self.balance = None
        self.transactionHistory = None
        self.transactions = [] # TransactionStruct
    
    def __repr__(self):
        return f'''Wallet(
    publicKey: {self.publicKey}
    privateKey: {self.privateKey}
    words: {self.words}
    address: {self.address}
    scripthash: {self.scripthash}
    balance: {self.balance}
    stats: {self.stats}
    banner: {self.banner})'''
    
    def init(self):
        ''' try to load, else generate and save '''
        if self.load():
            self.regenerate()
        else:
            self.generate()
            self.save()
        self.get()

    def load(self):
        wallet = WalletApi.load(
            walletPath=config.walletPath('wallet.yaml'))
        if wallet == False:
            return False
        self._entropy = wallet.get('entropy')
        self.publicKey = wallet.get('publicKey')
        self.privateKey = wallet.get('privateKey')
        self.words = wallet.get('words')
        self.address = wallet.get('address')
        self.scripthash = wallet.get('scripthash')
        if self._entropy is None:
            return False
        return True

    def save(self):
        WalletApi.save(
            wallet={
                'entropy': self._entropy,
                'publicKey': self.publicKey,
                'privateKey': self.privateKey,
                'words': self.words,
                'address': self.address,
                'scripthash': self.scripthash,
                },
            walletPath=config.walletPath('wallet.yaml'))

    def regenerate(self):
        self.generate()
        
    def generate(self):
        self._entropy = self._entropy or self._generateEntropy()
        self._privateKeyObj = self._generatePrivateKey()
        self._addressObj = self._generateAddress()
        self.words = self.words or self._generateWords()
        self.privateKey = self.privateKey or str(self._privateKeyObj)
        self.publicKey = self.publicKey or self._privateKeyObj.pub.hex()
        self.address = self.address or str(self._addressObj)
        self.scripthash = self.scripthash or self._generateScripthash()


    def _generateScripthash(self):
        # possible shortcut:
        #self.scripthash = '76a914' + [s for s in self._addressObj.to_scriptPubKey().raw_iter()][2][1].hex() + '88ac'
        from base58 import b58decode_check
        from binascii import hexlify
        from hashlib import sha256
        import codecs
        OP_DUP = b'76'
        OP_HASH160 = b'a9'
        BYTES_TO_PUSH = b'14'
        OP_EQUALVERIFY = b'88'
        OP_CHECKSIG = b'ac'
        DATA_TO_PUSH = lambda address: hexlify(b58decode_check(address)[1:])
        sig_script_raw = lambda address: b''.join((OP_DUP, OP_HASH160, BYTES_TO_PUSH, DATA_TO_PUSH(address), OP_EQUALVERIFY, OP_CHECKSIG))
        scripthash = lambda address: sha256(codecs.decode(sig_script_raw(address), 'hex_codec')).digest()[::-1].hex()
        return scripthash(self.address);

    def _generateEntropy(self):
        #return m.to_entropy(m.generate())
        return os.urandom(32)

    def _generateWords(self):
        return mnemonic.Mnemonic('english').to_mnemonic(self._entropy)

    def _generatePrivateKey(self):
        ravencoin.SelectParams('mainnet')
        return CRavencoinSecret.from_secret_bytes(self._entropy)

    def _generateAddress(self):
        return P2PKHRavencoinAddress.from_pubkey(self._privateKeyObj.pub)

    def showStats(self):
        ''' returns a string of stats properly formatted '''
        def invertDivisibility(divisibility:int):
            return (16 + 1) % (divisibility + 8 + 1);
        
        divisions = self.stats.get('divisions', 8)
        circulatingSats = self.stats.get('sats_in_circulation', 100000000000000) / int('1' + ('0'*invertDivisibility(int(divisions))))
        headTail = str(circulatingSats).split('.')
        if headTail[1] == '0' or headTail[1] == '00000000':
            circulatingSats = f"{int(headTail[0]):,}"
        else:
            circulatingSats = f"{int(headTail[0]):,}" + '.' + f"{headTail[1][0:4]}" + '.' + f"{headTail[1][4:]}"
        return f'''
    Circulating Supply: {circulatingSats}
    Decimal Points: {divisions}
    Reissuable: {self.stats.get('reissuable', False)}
    Issuing Transactions: {self.stats.get('source', {}).get('tx_hash', 'a015f44b866565c832022cab0dec94ce0b8e568dbe7c88dce179f9616f7db7e3')}
    '''
        
    def showBalance(self, rvn=False):
        ''' returns a string of balance properly formatted '''
        def invertDivisibility(divisibility:int):
            return (16 + 1) % (divisibility + 8 + 1);
        
        if rvn:
            balance = self.rvn / int('1' + ('0'*8))
        else:
            balance = self.balance / int('1' + ('0'*invertDivisibility(int(self.stats.get('divisions', 8)))))
        headTail = str(balance).split('.')
        if headTail[1] == '0':
            return f"{int(headTail[0]):,}"
        else:
            return f"{int(headTail[0]):,}" + '.' + f"{headTail[1][0:4]}" + '.' + f"{headTail[1][4:]}"
        
    def get(self, allWalletInfo=False):
        ''' gets data from the blockchain, saves to attributes '''
        x = Ravencoin(self.address, self.scripthash)
        x.get(allWalletInfo)
        self.balance = x.balance
        self.stats = x.stats
        self.banner = x.banner
        self.rvn = x.rvn
        self.transactionHistory = x.transactionHistory
        self.transactions = x.transactions
    
    def sign(self, message:str):
        return sign.signMessage(self._privateKeyObj, sign.Message(message))
    
    def verify(self, message:str, sig:bytes):
        return sign.verifyMessage(self.address, sign.Message(message), sig)    

and the entire sign functioanlity:

import sys
_bchr = lambda x: bytes([x])
_bord = lambda x: x[0]
from io import BytesIO as _BytesIO
import ravencoin
from ravencoin import signmessage
from ravencoin.wallet import CRavencoinSecret

class Message(str):   
    '''
    a Message is just a string with these monkey patched functions
    since python-ravencoinlib expects them to be present.
    '''
    
    def GetHash(self):
        return ravencoin.core.Serializable.GetHash(self)
    
    def serialize(self, params={}):
        f = _BytesIO()
        return f.getvalue()

def makeMessage(message:str):
    return Message(message)

def signMessage(key:CRavencoinSecret, message:Message):
    ''' returns binary signature '''
    return signmessage.SignMessage(key, message)

def verifyMessage(address:str, message:Message, sig:bytes):
    ''' returns success bool '''
    return signmessage.VerifyMessage(address, message, sig)
hst337

hst337

Public key is hex, just use Base.decode16(key, case: :lower)

LegitStack

LegitStack OP

iex(6)> :crypto.verify(:ecdsa, :sha256, "message", Base.decode64!("IFdGdzqI9fJJDbTASGbamHFQ7hlIT07jLALhYRhMrRY3QvKJuL2q8ojtwKsubj0EVtWJtlM8MbgmpvIaKwpjc04="), [Base.decode16("034e328758d422ce5c3a17c15528df1216ef0eaf845147876eea82d139755129a0", case: :lower), :secp256k1])
** (ArgumentError) argument error
    (crypto 5.0.4) :crypto.pkey_verify_nif(:ecdsa, :sha256, "message", <<32, 87, 70, 
119, 58, 136, 245, 242, 73, 13, 180, 192, 72, 102, 218, 152, 113, 80, 238, 25, 72, 79, 78, 227, 44, 2, 225, 97, 24, 76, 173, 22, 55, 66, 242, 137, 184, 189, 170, 242, 136, 237, 192, 171, 46, 110, 61, 4, 86, 213, ...>>, {{{:prime_field, <<255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 255, 255, 252, 47>>}, {<<0>>, "\a", :none}, <<4, 121, 190, 102, 126, 249, 220, 187, 172, 85, 160, 98, 149, 206, 135, 11, 7, 2, 155, 
252, 219, 45, 206, 40, 217, 89, 242, 129, 91, 22, 248, 23, 152, 72, 58, 218, 119, 38, 163, 196, 101, 93, 164, 251, 252, 14, ...>>, <<255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 186, 174, 220, 230, 175, 72, 160, 59, 191, 210, 94, 140, 208, 54, 65, 65>>, <<1>>}, {:ok, <<3, 78, 50, 135, 88, 212, 34, 206, 92, 58, 23, 193, 85, 40, 223, 18, 22, 239, 14, 175, 132, 81, 71, 135, 110, 234, 130, 209, 57, 117, 81, 41, 160>>}}, [])
    (crypto 5.0.4) crypto.erl:1420: :crypto.verify/6
iex(6)> :crypto.verify(:ecdsa, :sha256, "message", Base.decode64!("IFdGdzqI9fJJDbTASGbamHFQ7hlIT07jLALhYRhMrRY3QvKJuL2q8ojtwKsubj0EVtWJtlM8MbgmpvIaKwpjc04="), [Base.decode16!("034e328758d422ce5c3a17c15528df1216ef0eaf845147876eea82d139755129a0", case: :lower), :secp256k1])
false
hst337

hst337

That’s nice, but could you please share a link to the sources?

Where Next?

Trending in Questions Top

jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
silverdr
Using Phoenix.LiveView.TagEngine as an EEx.Engine is deprecated! To compile HEEx, use Phoenix.LiveView.TagEngine.compile/2 instead. Sta...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New

We're in Beta

About us Mission Statement