How to use @arkecosystem/crypto - 10 common examples

To help you get started, we’ve selected a few @arkecosystem/crypto examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ArkEcosystem / core / __tests__ / utils / fixtures / testnet / delegates.ts View on Github external
export const delegates: any = secrets.map(secret => {
    const publicKey = crypto.getKeys(secret).publicKey;
    const address = crypto.getAddress(publicKey);
    const balance = genesisTransactions.find(
        transaction => transaction.recipientId === address && transaction.type === 0,
    ).amount;
    return {
        secret,
        passphrase: secret, // just an alias for delegate secret
        publicKey,
        address,
        balance,
    };
});
github ArkEcosystem / core / packages / core-test-utils / fixtures / testnet / delegates.js View on Github external
module.exports = delegatesConfig.secrets.map(secret => {
  const publicKey = crypto.getKeys(secret).publicKey
  const address = crypto.getAddress(publicKey)
  const balance = genesisTransactions.find(
    transaction =>
      transaction.recipientId === address && transaction.type === 0,
  ).amount
  return {
    secret,
    passphrase: secret, // just an alias for delegate secret
    publicKey,
    address,
    balance,
  }
})
github ArkEcosystem / core / __tests__ / helpers / transaction-factory.ts View on Github external
for (let i = 0; i < quantity; i++) {
            if (this.builder.constructor.name === "TransferBuilder") {
                // @FIXME: when we use any of the "withPassphrase*" methods the builder will
                // always remember the previous vendor field instead generating a new one on each iteration
                const vendorField: string = this.builder.data.vendorField;

                if (!vendorField || (vendorField && vendorField.startsWith("Test Transaction"))) {
                    this.builder.vendorField(`Test Transaction ${i + 1}`);
                }
            }

            if (this.builder.constructor.name === "DelegateRegistrationBuilder") {
                // @FIXME: when we use any of the "withPassphrase*" methods the builder will
                // always remember the previous username instead generating a new one on each iteration
                if (!this.builder.data.asset.delegate.username) {
                    this.builder = Transactions.BuilderFactory.delegateRegistration().usernameAsset(
                        this.getRandomUsername(),
                    );
                }
            }

            if (this.version) {
                this.builder.version(this.version);
            }

            if (this.fee) {
                this.builder.fee(this.fee.toFixed());
            }

            if (this.timestamp) {
                this.builder.data.timestamp = this.timestamp;
            }
github ArkEcosystem / core / packages / core-state / src / stores / state.ts View on Github external
public setLastBlock(block: Interfaces.IBlock): void {
        // Only keep blocks which are below the new block height (i.e. rollback)
        if (this.lastBlocks.last() && this.lastBlocks.last().data.height !== block.data.height - 1) {
            assert(block.data.height - 1 <= this.lastBlocks.last().data.height);
            this.lastBlocks = this.lastBlocks.filter(b => b.data.height < block.data.height);
        }

        this.lastBlocks = this.lastBlocks.set(block.data.height, block);

        Managers.configManager.setHeight(block.data.height);

        if (Managers.configManager.isNewMilestone()) {
            app.resolvePlugin("event-emitter").emit("internal.milestone.changed");
        }

        Transactions.TransactionRegistry.updateStaticFees(block.data.height);

        // Delete oldest block if size exceeds the maximum
        if (this.lastBlocks.size > app.resolveOptions("state").storage.maxLastBlocks) {
            this.lastBlocks = this.lastBlocks.delete(this.lastBlocks.first().data.height);
        }
    }
github nos / client / src / renderer / shared / util / ARK / sendARK.js View on Github external
export default async function sendARK({ amount, receiver, wif, fee = 0 }) {
  if (!Identities.Address.validate(receiver)) {
    throw new Error(`Invalid script hash: "${receiver}"`);
  }
  if (amount <= 0) {
    throw new Error(`Invalid amount: "${amount}"`);
  }

  console.log('Amount ', amount);
  console.log('receiver ', receiver);
  console.log('wif ', wif);

  const send = async () => {
    try {
      // https://github.com/ArkEcosystem/core/blob/1cbc2a05a596340d4f261d162b8f426815908db6/packages/crypto/src/transactions/builders/transactions/transaction.ts
      const transaction = Transactions.BuilderFactory.transfer() // specify 'transfer' as our AIP11 transaction type
        .network(23)
        .version(2)
github ArkEcosystem / core / packages / core-database / lib / wallet-manager.js View on Github external
async applyTransaction (transaction) {
    const transactionData = transaction.data
    const recipientId = transactionData.recipientId

    const sender = this.getWalletByPublicKey(transactionData.senderPublicKey)
    let recipient = recipientId ? this.getWalletByAddress(recipientId) : null

    if (!recipient && recipientId) { // cold wallet
      recipient = new Wallet(recipientId)
      this.walletsByAddress[recipientId] = recipient
      emitter.emit('wallet:cold:created', recipient)
    } else if (transactionData.type === TRANSACTION_TYPES.DELEGATE_REGISTRATION && this.walletsByUsername[transactionData.asset.delegate.username.toLowerCase()]) {
      logger.error(`Delegate transction sent by ${sender.address}`, JSON.stringify(transactionData))

      throw new Error(`Can't apply transaction ${transactionData.id}: delegate name already taken`)
    } else if (transactionData.type === TRANSACTION_TYPES.VOTE && !this.walletsByPublicKey[transactionData.asset.votes[0].slice(1)].username) {
      logger.error(`Vote transaction sent by ${sender.address}`, JSON.stringify(transactionData))

      throw new Error(`Can't apply transaction ${transactionData.id}: voted delegate does not exist`)
    } else if (config.network.exceptions[transactionData.id]) {
      logger.warn('Transaction forcibly applied because it has been added as an exception:', transactionData)
    } else if (!sender.canApply(transactionData)) {
      logger.error(`Can't apply transaction for ${sender.address}`, JSON.stringify(transactionData))
      logger.debug('Audit', JSON.stringify(sender.auditApply(transactionData), null, 2))

      throw new Error(`Can't apply transaction ${transactionData.id}`)
    }

    sender.applyTransactionToSender(transactionData)

    if (recipient && transactionData.type === TRANSACTION_TYPES.TRANSFER) {
      recipient.applyTransactionToRecipient(transactionData)
github ArkEcosystem / core / packages / core-database / lib / wallet-manager.js View on Github external
async revertBlock (block) {
    let delegate = this.getWalletByPublicKey(block.data.generatorPublicKey)

    if (!delegate) {
      const generator = crypto.getAddress(block.data.generatorPublicKey, config.network.pubKeyHash)

      delegate = new Wallet(generator)
      delegate.publicKey = block.data.generatorPublicKey

      this.reindex(delegate)
    }

    const revertedTransactions = []

    try {
      // TODO Use Promise.all or explain why not
      // - Promise.each is applied sequentially
      // - Promise.all is applied in parallel
      await Promise.each(block.transactions, async (transaction) => {
        await this.revertTransaction(transaction)
github ArkEcosystem / core / packages / core-database / lib / interface.js View on Github external
async verifyTransaction(transaction) {
    const senderId = crypto.getAddress(
      transaction.data.senderPublicKey,
      config.network.pubKeyHash,
    )

    const sender = this.walletManager.findByAddress(senderId) // should exist

    if (!sender.publicKey) {
      sender.publicKey = transaction.data.senderPublicKey
      this.walletManager.reindex(sender)
    }

    const dbTransaction = await this.getTransaction(transaction.data.id)

    return sender.canApply(transaction.data, []) && !dbTransaction
  }
github ArkEcosystem / core / packages / core-blockchain / lib / blockchain.js View on Github external
/* eslint max-len: "off" */
/* eslint no-await-in-loop: "off" */

const { slots } = require('@arkecosystem/crypto')
const { Block } = require('@arkecosystem/crypto').models
const app = require('@arkecosystem/core-container')

const logger = app.resolvePlugin('logger')
const config = app.resolvePlugin('config')
const emitter = app.resolvePlugin('event-emitter')
const delay = require('delay')
const pluralize = require('pluralize')
const stateMachine = require('./state-machine')
const Queue = require('./queue')

module.exports = class Blockchain {
  /**
   * Create a new blockchain manager instance.
   * @param  {Boolean} networkStart
   * @return {void}
   */
github ArkEcosystem / core / packages / core-forger / lib / manager.js View on Github external
/* eslint no-await-in-loop: "off" */

const delay = require('delay')

const container = require('@arkecosystem/core-container')

const logger = container.resolvePlugin('logger')
const config = container.resolvePlugin('config')

const { slots } = require('@arkecosystem/crypto')
const { Delegate, Transaction } = require('@arkecosystem/crypto').models

const isEmpty = require('lodash/isEmpty')
const uniq = require('lodash/uniq')
const pluralize = require('pluralize')

const Client = require('./client')

module.exports = class ForgerManager {
  /**
   * Create a new forger manager instance.
   * @param  {Object} options
   */
  constructor(options) {
    this.secrets = config.delegates ? config.delegates.secrets : null
    this.network = config.network
    this.client = new Client(options.hosts)