【问题标题】:Django Validate Bitcoin AddressDjango 验证比特币地址
【发布时间】:2016-06-12 05:16:25
【问题描述】:

我想要一个接受用户比特币地址的 Django 表单。验证此地址是否合法的最佳方法是什么?

我可以尝试编写自己的实现,但关于这些事情,我认为使用经过尝试和测试的东西总是比创建有潜在漏洞的东西更好。是否有好的 python 代码可以用来为我的 django 表单或任何已经完成此操作的资源创建自定义字段?

或者,是否最好跳过整个自定义表单字段过程,例如,使用 pycoin 库验证视图中的地址?但是,如果我这样做,我将如何在表单中返回错误?

【问题讨论】:

    标签: django bitcoin


    【解决方案1】:

    BCAddressField 完全符合我的要求。但是请注意,您必须将 from django.forms.util import ValidationError 替换为 from django.core.exceptions import ValidationError,因为前者已被弃用。

    【讨论】:

      【解决方案2】:

      Bech32:

      def btc_validation(address):
          a = str(address)
          length = 0
          valid = False
          not_btc = False
          for i in a:
              length += 1
          if length == 42:
              if a[2] == '1' and a[0] == 'b' and a[1] == 'c':
                  for i in a:
                      if i == 'O' or i == 'I':
                          not_btc = True
                          break
                  if not_btc == True:
                      return valid 
                  else:
                      valid = True
                      return valid
      
              else:
                  return 'didn\'t start with bc1'
          else:
              return 'it\'s short'
      

      P2PKH:

      import base58
      
      def bitcoin_address_validation(bitcoinAddress):
          """
          Base58 (P2PKH)
          """
          try:
              base58Decoder = base58.b58decode(bitcoinAddress).hex()
              prefixAndHash = base58Decoder[:len(base58Decoder) - 8]
              checksum = base58Decoder[len(base58Decoder) - 8:]
              hash = prefixAndHash
              for x in range(1, 3):
                  hash = hashlib.sha256(binascii.unhexlify(hash)).hexdigest()
              if (checksum == hash[:8]):
                  valid = True
              else:
                  valid = False
          except:
              valid = False
              pass
          return valid
      

      Reference

      【讨论】:

        猜你喜欢
        • 2014-02-28
        • 2018-04-28
        • 2019-05-16
        • 2021-10-21
        • 2014-01-17
        • 2019-04-05
        • 2020-09-18
        • 1970-01-01
        • 2021-04-15
        相关资源
        最近更新 更多