libsecp256k1 與 openssl ecdsa

1. 歷史

區塊鏈節點在接收到的用戶發送的交易時,首先會驗證交易所涉及utxo的可用性。方法是驗證用戶簽名的合法性,涉及的簽名算法就是secp256k1,一種橢圓曲線加密算法。node

長期以來,實現了該算法的第三方庫只有openssl,所以btcoin core一直都引用了此庫。git

openssl是一個龐大的開源庫,不單單實現了橢圓曲線加密算法,在橢圓曲線加密算法中也不單單實現了secp256k1這一種橢圓曲線。github

不久你們就發現了openssl的一些問題,除了自身結構複雜龐大,文檔也不全面,最重要的是,opensssl的算法一致性也有潛在的問題,這會致使區塊鏈發生不可預料的分叉,形成難以估量的損失。算法

如下是來自BIP66中的說明:網絡

--BIP66 --
"Bitcoin's reference implementation currently relies on OpenSSL for signature validation, which means it is implicitly defining Bitcoin's block validity rules. Unfortunately, OpenSSL is not designed for consensus-critical behaviour (it does not guarantee bug-for-bug compatibility between versions), and thus changes to it can - and have - affected Bitcoin software.區塊鏈

One specifically critical area is the encoding of signatures. Until recently, OpenSSL's releases would accept various deviations from the DER standard and accept signatures as valid. When this changed in OpenSSL 1.0.0p and 1.0.1k, it made some nodes reject the chain.ui

This document proposes to restrict valid signatures to exactly what is mandated by DER, to make the consensus rules not depend on OpenSSL's signature parsing. A change like this is required if implementations would want to remove all of OpenSSL from the consensus code."this

因此自2016年2月13日起,在新發布的bitcoin core 0.12.0版本中,libsecp256k1庫代替了openssl ecdsa。 libsecp256k1中只實現了一種橢圓曲線算法,代碼簡練,很快大部分社區就接收了這種改變。加密

2. 區別

  • 在基於橢圓曲線secp256k1的加解密算法的實現上,libsecp256k1 與 openssl ecdsa不一致,你若使用openssl ecdsa對交易簽名,如今的區塊鏈可能不會正確驗證。
  • libsecp256k1已經成爲bitcoin社區事實上的標準,成爲開發者惟一能選擇的官方庫
  • libsecp256k1 與 openssl ecdsa的主要差異之一,在於bip62提出的"Low S values in signatures"規則。libsecp256k1中包含了對規則的自動應用,而openssl ecdsa須要開發者本身實現該規則。

3. 關於"Low S values in signatures"規則

在BIP中描述以下:rest

--BIP62--
"Low S values in signatures

The value S in signatures must be between 0x1 and 0x7FFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF 5D576E73 57A4501D DFE92F46 681B20A0 (inclusive). If S is too high, simply replace it by S' = 0xFFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141 - S."

關於"Low S values in signatures"的必要性,有一段解釋以下:

"Absent this rule, any person is able to take a Bitcoin transaction, flip s in any of its signatures, and push the transaction out again with a different TXID. Being able to do this only changes the hash of the transaction, and does not alter its validity in any way. Being able to mutate transactions breaks a number of potentially interesting transaction types in Bitcoin like payment channels, where chains of transactions will suddenly be invalidated by a parent being mutated and an alternate form included in a block.

By forcing valid transactions to always have low s this ability is removed, though a person with the private key for a transaction is still able to mutate their own transactions by resigning them with a new nonce."

簡言之,其目的是,防止惡意第三方經過修改transaction(按照以往ecdsa規則,修改後依然合法)影響區塊鏈網絡運行,同時依然保障私鑰全部者生成多樣transaction的能力。

相關實現能夠參考早期的bitcoin代碼

4. 引用

相關文章
相關標籤/搜索