Обзор по интеграции#

Эта документация также доступна в формате PDF.

Dash Core is a fork of Bitcoin Core and shares many common functionalities. Key differences are found in existing JSON-RPC commands which have been customized to support unique functionalities such as InstantSend.

The Basics#

Dash is a Proof of Work network, and similar to Bitcoin, Dash has a mining network but uses a different block hashing algorithm. Dash serves as an improvement of Bitcoin’s shortcomings by offering a robust solution for instant transactions, enhancing user privacy, and offering a self-sustainable decentralized governance model.

JSON-RPC Interface#

The majority of commands are unchanged from Bitcoin making integration into existing systems relatively straightforward. Note that the following commands have been modified to support InstantSend:

Block Hashing Algorithm#

Dash uses the X11 algorithm in place of SHA256 used in Bitcoin. It’s important to note, however, that this only affects the hashing of the block itself. All other internals utilize SHA256 hashes (transactions, merkle root, etc.), which allows for most existing libraries to work in the Dash ecosystem.

Специальные транзакции#

Dash Core v0.13.x introduced the concept of “Special Transactions”. Please see the Transaction Type Integration Guide for more information.

Специальные транзакции#

Эта документация также доступна в формате PDF.

Dash 0.13.0 and higher implement DIP002 Special Transactions, which form a basis for new transaction types that provide on-chain metadata to assist various consensus mechanisms. The following special transaction types exist:

Релиз

Версия

Тип

Размер нагрузки

Нагрузка

Нагрузка JSON

Назначение транзакции

v0.13.0

3

0

n/a

n/a

n/a

Стандартная транзакция

v0.13.0

3

1

<variable int>

<hex>

proRegTx

Masternode Registration

v0.13.0

3

2

<variable int>

<hex>

proUpServTx

Update Masternode Service

v0.13.0

3

3

<variable int>

<hex>

proUpRegTx

Update Masternode Operator

v0.13.0

3

4

<variable int>

<hex>

proUpRevTx

Masternode Revocation

v0.13.0

3

5

<variable int>

<hex>

cbTx

Masternode List Merkle Proof

v0.13.0

3

6

<variable int>

<hex>

qcTx

Quorum Commitment

Примечания по интеграции:

  1. DIP002 Специальные тразакции - основной компонент Dash Core v0.13.0, он вводит новые версии транзакций и соответствующую им «Нагрузку» сети

  2. Integrated Systems must be able to serialize and deserialize these new Transaction Types to accurately encode and decode Raw Transaction data.

  3. С точки зрения обратной совместимости, 4-байтная (32-bit) поле версии, включённое в Старые транзакции, было разделено на два поля: версия и тип (каждое состоит из 2 байтов).

  4. Refer to the Special Transactions section of the dash developer reference for additional detail on these data types, e.g. <variable int>.

  5. InstantSend status and Payload JSON (e.g. proRegTx) is included in the JSON-RPC response, please note that this data is not part of the calculated hash and is provided for convenience.

Чтобы увидеть рабочие примеры каждого типа транзакций, смотрите документацию по интеграции типов транзакций v0.13.0 (PDF) .

InstantSend#

This documentation is also available as a PDF.

InstantSend is a feature provided by the Dash network that allows for zero-confirmation transactions to be safely accepted and re-spent. The network attempts to lock the inputs of every valid transaction when it is broadcast to the network. Every secured transaction is included in a following block in accordance with standard blockchain principles.

InstantSend is enabled by the Masternode Network which comprises approximately 5,000 masternode servers. These nodes are differentiated from standard nodes by having proven ownership of 1,000 Dash, making the network highly resistant to Sybil attacks. Masternodes form Long-Living Masternode Quorums (LLMQs), which are responsible for providing near-instant certainty to the transaction participants that the transaction inputs cannot be respent, and that the transaction will be included in a following block instead of a conflicting transaction.

This concept works as an extension to Nakamoto Consensus. InstantSend enables transacted funds to be immediately and securely respent by the recipient, even before the transaction is included in a block.

Получение транзакций InstantSend#

Вводится два требования для получения транзакций InstantSend:

  1. Возможность определить «статус InstantSend» в заданной транзакции.

  2. Возможность настройки «статуса подтверждения» независимо от подтверждения блока.

InstantSend Status обычно определяется через прямое соединение с демоном dash, уведомление ZMQ, или с помощью сценария уведомления внешнего кошелька.

Прямое соединение: Статус InstantSend может быть идентифицирован через прямое соединение с демоном Dash с использованием протокола JSON-RPC. Атрибут «instantlock» ответа JSON отражает состояние транзакции и включён в следующие команды:

ZMQ Notification: Whenever a transaction enters the mempool and whenever a transaction is locked in the mempool, ZMQ notifications can be broadcast by the node. A list of possible ZMQ notifications can be found here.

The following notifications are relevant for recognizing transactions and their corresponding instantlocks:

  • zmqpubhashtx

  • zmqpubhashtxlock

  • zmqpubrawtx

  • zmqpubrawtxlock

Уведомление кошелька: Dash Core Daemon можно настроить для выполнения внешнего скрипта всякий раз, когда выполняется транзакция InstantSend, связанная с конкретным кошельком. Настройка производится путём добавления следующей строки в файл dash.conf:

instantsendnotify=/path/to/concurrent/safe/handler %s

This is typically used with a wallet that has been populated with watch-only addresses.

Распространение транзакций InstantSend#

Since Dash v0.14.0 established LLMQs on the Dash network, quorums will now attempt to lock every valid transaction by default without any additional fee or action by the sending wallet or user. A transaction is eligible for InstantSend when each of its inputs is considered confirmed. This is the case when at least one of the following circumstances is true:

  • the previous transaction referred to by the input is confirmed with 6 blocks

  • the previous transaction is confirmed through an older InstantSend lock

  • the block containing the previous transaction is ChainLocked

When checking the previous transaction for an InstantSend lock, it is important to do this on mempool (non-mined) transactions. This allows chained InstantSend locking.

Дополнительные ресурсы#

Следующие ресурсы предоставляют дополнительную информацию о функции InstantSend и предназначены для обеспечения более полного понимания базовых технологий.

Сервисы API#

Существует несколько API, которые облегчают быструю и простую интеграцию с сетью Dash для таких сервисов как:

  • Распространение транзакций

  • Обменные курсы

  • Конвертация валюты

  • Генерация счетов

API обычно используются для того, чтобы устранить необходимость запуска собственной инфраструктуры для поддержки взаимодействия с блокчейном. Сюда входят такие механизмы, как:

  • Формирование и распространение транзакций в сети.

  • Генерация адресов с использованием HD кошельков.

  • Обработка платежей с использованием WebHooks.

Существует множество вариантов поддержки этих методов, ключевым отличием которых является включённая модель ценообразования и поддерживаемые функции. В следующем списке провайдеров API выполнена попытка описать эти ключевые функции/дифференциаторы, также в него включена ссылка на соответствующую документацию.

Insight#

../../../_images/insight.png

dashevo/insight-api

Dash Insight REST API c открытым кодом - это удобный, мощный и простой способ считывать данные из сети Dash и разрабатывать с его помощью свои собственные сервисы. Практическое руководство по Insight API и Insight UI обозревателю блоков доступно тут.

  • Функции: передача транзакций в сеть, уведомления WebSocket.

  • Модель ценообразования: бесплатный / открытый источник

  • Документация: dashevo/insight-api

BlockCypher#

../../../_images/blockcypher.png

https://www.blockcypher.com

BlockCypher представляет собой простой, в основном RESTful JSON API для взаимодействия с блокчейнами, доступ к которому осуществляется через HTTP или HTTPS из домена api.blockcypher.com.

  • Функции: обработка транзакций, кошелёк HD / генерация адресов, обратные вызовы WebSocket и WebHook, а также перенаправление платежей. BlockCypher не обрабатывает приватные ключи.

  • Pricing Model: Per API Call, 5000 Requests -> $85.00 per month (https://accounts.blockcypher.com)

  • Документация: https://www.blockcypher.com/dev/dash/

BitGo#

../../../_images/bitgo.png

https://www.bitgo.com

BitGo предоставляет простой и надёжный RESTful API и SDK для интеграции кошельков, поддерживающих цифровую валюту, с вашим приложением. Доступна поддержка Dash InstantSend.

  • Функции: HD-кошельки с мультиподписью, операции с кошельком, уведомления WebSocket и WebHook, кастодиальные решения

  • Модель ценообразования: за API запрос

  • Documentation: https://app.bitgo.com/docs/

ChainRider#

../../../_images/chainrider.png

https://www.chainrider.io

ChainRider - облачный сервис, предоставляющий набор из нескольких REST API для управления цифровой валютой

  • Функции: блокчейн-запросы, уведомления о событиях, обработка транзакций, обработка платежей и т.п.

  • Модель ценообразования: бесплатно в течение пробного периода, оплата за API вызов

  • Documentation: https://www.chainrider.io/docs/dash/

Blockmove#

../../../_images/blockmove.png

https://blockmove.io

Сryptocurrency wallet, merchant & API provider. Blockmove is a simple and easy way to start accepting payments in cryptocurrency.

  • Features: Non-custodial wallet, HD Wallet, High anonymity, Low fees. Private keys are not stored and are available only to the user.

  • Pricing Model: API - 0.3% for withdrawal transactions. Merchant - 1 year free, then $49/month

  • Documentation: https://docs.blockmove.io

NOWNodes#

../../../_images/nownodes.png

https://nownodes.io/

NOWNodes provides simple, fast, and secure RPC access to Dash-based full nodes. The low latency and high performance is of great use to researchers and businesses such as crypto miners or hardware wallet providers.

CoinPayments#

../../../_images/coinpayments.png

https://www.coinpayments.net

CoinPayments is an integrated payment gateway for cryptocurrencies such as Dash. Shopping cart plugins are available for all popular webcarts used today. CoinPayments can help you set up a new checkout or integrate with your pre-existing checkout.

  • Features: Invoicing, Exchange Rates, WebHook Callbacks. CoinPayments holds Private Keys on their server allowing merchants to withdraw funds in Cryptocurrency or convert to fiat.

  • Интеграции: aMember Pro, Arastta, Blesta, BoxBilling, Drupal, Ecwid, Hikashop, Magento, OpenCart, OSCommerce, PrestaShop, Tomato Cart, WooCommerce, Ubercart, XCart, ZenCart

  • Модель ценообразования: комиссия за обработку в размере 0,5% (https://www.coinpayments.net/help-fees)

  • Документация: https://www.coinpayments.net/apidoc

Ресурсы SDK#

SDK (набор средств для разработки) используются для ускорения проектирования и разработки продуктов в сети Dash. Эти ресурсы могут использоваться как для взаимодействия с провайдером API, так и для создания автономных приложений путём формирования транзакций и/или выполнения различных функций кошелька.

Руководство для разработчиков Dash#

../../../_images/dash-logo.png

https://dashcore.readme.io/

The Dash Developer Portal aims to provide the information you need to understand Dash and start building Dash-based applications. To make the best use of this documentation, you may want to install the current version of Dash Core and Dash Platform, either from source, from a pre-compiled executable or from Docker Hub.

NodeJS/JavaScript: Dashcore#

../../../_images/bitcore.png

https://bitcore.io

Dashcore является форком Bitcore и работает как полная нода Dash - ваши приложения запускаются непосредственно в децентрализованной сети. Для разработки приложений кошелька в Dash были добавлены дополнительные индексы для запроса балансов адресов, истории транзакций и неизрасходованных выходов.

NodeJS/JavaScript: DashJS#

DashJS allows you to transact on L1 or fetch/register documents on L2 within a single library, including management and signing of your documents.

PHP: Bitcoin-PHP#

Bit-Wasp/bitcoin-php

Bitcoin-PHP - это реализация Bitcoin с поддержкой Dash, которая в основном использует только PHP.

Python: PyCoin#

richardkiss/pycoin

PyCoin - это реализация ряда вспомогательных утилит, которые могут быть полезны при работе с Bitcoin и Dash. Он тестировался с Python 2.7, 3.6 и 3.7.

Java: DashJ#

../../../_images/bitcoinj.png

dashevo/dashj

DashJ - это библиотека для работы с протоколом Dash. В ней реализована поддержка кошелька, с её помощью можно отправлять/получать транзакции (включая InstantSend), не нуждаясь в локальной копии Dash Core, также она имеет много других дополнительных функций. Реализована на Java, но может использоваться с любым совместимым с JVM языком: присутствуют примеры в Python и JavaScript.

Objective-C: Dash-Sync#

../../../_images/dash-logo.png

dashevo/dashsync-iOS

Dash-Sync это блокчейн-фреймворк Dash для iOS на Objective-C. Он реализует большинство релевантных Предложений по улучшению Bitcoin (BIPs) и Предложений по улучшению Dash (DIPs).

.NET: NBitcoin#

../../../_images/dash-logo.png

MetacoSA/NBitcoin

NBitcoin is the most complete Bitcoin library for the .NET platform and has been patched to include support for Dash. It implements all most relevant Bitcoin Improvement Proposals (BIPs) and Dash Improvement Proposals (DIPs). It also provides low level access to Dash primitives so you can easily build your application on top of it.

BlockCypher#

../../../_images/blockcypher.png

https://www.blockcypher.com

BlockCypher также предлагает SDK.

Торговые автоматы#

Community member moocowmoo has released code to help merchants build their own vending machine and set it up to receive Dash InstantSend payments. The Dashvend software can also be used to create any sort of payment system, including point-of-sale systems that can accept InstantSend payments.

Ценовые тикеры#

You can add a simple price ticker widget to your website using the simple code snippet generator from CoinGecko.

Аналогичные виджеты с различным дизайном доступны на CoinLibWorldCoinIndex и Cryptonator, в то время как API, предоставляющий аналогичную информацию, размещён на DashCentral.

QR-коды#

Many wallets can generate QR codes that are scannable to simplify entry of the Dash address. Printing these codes or posting the on your website makes it easy to receive payment and tips in Dash, both online and offline.

  • In Dash Core, go to the Receive tab, generate an address if necessary, and double-click it to display a QR code. Right-click on the QR code and select Save Image to save a PNG file.

  • В кошельке Dash для Android нажмите Запросить средства, а затем нажмите на QR-код, чтобы отобразить его увеличенное изображение. Для сохранения этого изображения вы можете сделать его скриншот.

  • В кошельке Dash для iOS проведите пальцем влево, чтобы отобразить экран Запросить средства. Появятся QR-код и адрес. Для сохранения этого изображения вы можете сделать его скриншот.

  • Чтобы сгенерировать QR-код из любого адреса Dash, посетите CWA QR Code Generator и просто вставьте свой адрес Dash для генерации изображения.