All files server.js

88.38% Statements 213/241
78.9% Branches 86/109
100% Functions 29/29
88.19% Lines 209/237

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729                                                        1x 1x   1x                                                                                                         6x   6x 1x   5x     6x 6x 6x 6x 6x 6x 6x 6x             6x               6x 6x 6x 6x 6x 6x 6x 6x 6x           6x 6x 6x       14x 3x   11x                                     18x 18x 1x     17x 2x 2x 2x         2x     15x 1x     14x 6x       6x 3x 3x 2x         2x               12x 1x         1x     11x                                 11x                         19x   19x                 19x               19x 2x     2x     17x               17x 5x     12x 12x     12x   12x 1x         1x       11x           11x 11x   1x 1x         1x   10x             2x 2x 2x           2x           2x               10x 1x   9x   9x 8x 8x 5x         3x 2x           1x     1x                 29x 29x       3x       1x       2x           2x 1x         1x 1x     1x       8x 8x     6x 6x 6x 6x   7x                 7x 7x 6x 1x             6x 2x 2x   4x 1x         1x     3x       3x           3x 3x 3x     3x                 3x 3x           1x 1x 1x       1x   2x 2x 2x           4x 2x   2x           5x     5x 5x     5x 5x   5x 3x 3x               3x 1x 1x 2x 2x 2x   3x       3x 2x 1x   1x         3x 3x 3x     2x   2x 2x 2x 2x             2x   2x   2x   2x 2x                   1x 1x               2x 2x   2x       2x 1x               1x   2x                 1x       1x   1x           1x 1x 1x   1x 1x     1x     1x   1x             1x                       1x                     1x   1x     1x 1x     1x         1x     1x           1x     1x           1x   1x               1x 1x           1x 1x 1x           1x 1x       1x      
/* @flow */
import logger from 'winston'
import AsyncLock from 'async-lock'
 
import {
  updateGlobalBlockHeight,
  makeUpdateZonefile,
  submitUpdate,
  checkTransactions,
  hash160,
  subdomainOpToZFPieces
} from './operations'
import {
  isRegistrationValid,
  isSubdomainRegistered,
  checkProofs
} from './lookups'
import { RegistrarQueueDB } from './db'
import type { SubdomainRecord, QueueRecord } from './db'
import {
  validateStacksAddress,
  publicKeyFromSignature,
  publicKeyToAddress,
  AddressVersion
} from '@stacks/transactions'
import type { SubdomainOp } from './operations'
import * as crypto from 'crypto'
 
const TIME_WEEK = 604800
const QUEUE_LOCK = 'queue'
 
export const SERVER_GLOBALS = { lastSeenBlockHeight: 0 }
 
type SubdomainResult = {
  name: string,
  address: string,
  sequence: number,
  zonefile: string,
  status: string,
  iterator: number,
};
 
export class SubdomainServer {
  domainName: string;
  ownerKey: string;
  paymentKey: string;
  zonefileSize: number;
  uriEntries: Array<{
    name: string,
    target: string,
    priority: number,
    weight: number,
  }>;
  disableRegistrationsWithoutKey: boolean;
  apiKeys: Array<string>;
  ipWhitelist: Array<string>;
  ipLimit: number;
  nameMinLength: number;
  proofsRequired: number;
  db: RegistrarQueueDB;
  lock: AsyncLock;
  checkCoreOnBatching: boolean;
  lastSeenBlock: number;
  minBatchSize: number;
  regtest: ?boolean;
 
  constructor(config: {
    domainName: string,
    ownerKey: string,
    paymentKey: string,
    dbLocation: string,
    domainUri?: ?string,
    resolverUri: ?string,
    zonefileSize: number,
    ipLimit: number,
    proofsRequired: number,
    disableRegistrationsWithoutKey: boolean,
    checkCoreOnBatching: boolean,
    apiKeys?: Array<string>,
    ipWhitelist?: Array<string>,
    nameMinLength: number,
    minBatchSize?: number,
    regtest?: boolean,
  }) {
    this.lastSeenBlock = 0
 
    if (config.minBatchSize) {
      this.minBatchSize = config.minBatchSize
    } else {
      this.minBatchSize = 1
    }
 
    this.domainName = config.domainName
    this.ownerKey = config.ownerKey
    this.paymentKey = config.paymentKey
    this.zonefileSize = config.zonefileSize
    this.ipWhitelist = config.ipWhitelist ? config.ipWhitelist : []
    this.uriEntries = []
    Eif (config.domainUri) {
      this.uriEntries.push({
        name: '_http._tcp',
        target: config.domainUri,
        priority: 10,
        weight: 1
      })
    }
    Iif (config.resolverUri) {
      this.uriEntries.push({
        name: '_resolver',
        target: config.resolverUri,
        priority: 10,
        weight: 1
      })
    }
    this.disableRegistrationsWithoutKey = config.disableRegistrationsWithoutKey
    this.apiKeys = config.apiKeys ? config.apiKeys : []
    this.ipLimit = config.ipLimit
    this.nameMinLength = config.nameMinLength
    this.proofsRequired = config.proofsRequired
    this.checkCoreOnBatching = config.checkCoreOnBatching
    this.db = new RegistrarQueueDB(config.dbLocation)
    this.lock = new AsyncLock()
    this.regtest = config.regtest
  }
 
  async initializeServer() {
    // reset global var -- this will only come up in testing,
    //  at runtime, it's one server instance per process
    SERVER_GLOBALS.lastSeenBlockHeight = 0
    await updateGlobalBlockHeight()
    await this.db.initialize()
  }
 
  isValidLength(subdomainName: string) {
    if (!this.nameMinLength) {
      return true
    } else {
      return subdomainName.length >= this.nameMinLength
    }
  }
 
  // returns a truth-y error message if request flags spam check
  //  returns false if the request is not spam
  async spamCheck(
    subdomainName: string,
    owner: string,
    zonefile: string,
    ipAddress: ?string,
    authorization: ?string
  ) {
    // the logic here is a little convoluted, because I'm trying to short-circuit
    //  the spam checks while also using Promises, which is a little tricky.
    // the logic should encapsulate:
    //
    //  spam pass = (ownerAddressGood && (apiKeyGood || (ipAddressGood && socialProofsGood)))
    //
    const ownerCount = await this.db.getOwnerAddressCount(owner)
    if (ownerCount >= 1) {
      return 'Owner already registered subdomain with this registrar.'
    }
 
    if (authorization && authorization.startsWith('bearer ')) {
      const apiKey = authorization.slice('bearer '.length)
      Eif (this.apiKeys.includes(apiKey)) {
        logger.info('Passed spam checks with API key', {
          msgType: 'spam_pass',
          reason: 'api_key',
          apiKey: apiKey.slice(0, 5)
        })
        return false
      }
    }
    if (this.disableRegistrationsWithoutKey) {
      return 'Registrations without API key are disabled'
    }
 
    if (this.ipLimit > 0) {
      Iif (!ipAddress) {
        return 'IP limiting in effect, and no IP address detected for request.'
      } else {
        // if it's not in the whitelist, perform a check
        if (!(this.ipWhitelist && this.ipWhitelist.includes(ipAddress))) {
          const ipCount = await this.db.getIPAddressCount(ipAddress)
          if (ipCount >= this.ipLimit) {
            logger.warn('IP limited by spam filter', {
              msgType: 'spam_fail',
              reason: 'ip_count',
              ip: ipAddress
            })
            return `IP address ${JSON.stringify(
              ipAddress
            )} already registered ${ipCount} subdomains.`
          }
        }
      }
    }
 
    if (!this.isValidLength(subdomainName)) {
      logger.warn(
        `Discarding operation for ${subdomainName}` +
          ` because subdomain shorter than ${this.nameMinLength} characters.`,
        { msgType: 'spam_fail', reason: 'name_length', ip: ipAddress }
      )
      return `NameLength: Username must be ${this.nameMinLength} characters or longer.`
    }
 
    Iif (this.proofsRequired > 0) {
      try {
        const proofsValid = await checkProofs(owner, zonefile)
        if (proofsValid.length < this.proofsRequired) {
          logger.warn('Proofs required for passing spam-check', {
            msgType: 'spam_fail',
            reason: 'proofs',
            ip: ipAddress
          })
          return `Proofs are required: had ${proofsValid.length} valid, requires ${this.proofsRequired}`
        }
      } catch (err) {
        logger.error(err)
        return 'Proof validation failed'
      }
    }
 
    return false
  }
 
  async queueRegistration(
    subdomainName: string,
    owner: string,
    sequenceNumber: number,
    zonefile: string,
    ipAddress: string = '',
    authorization: ?string = ''
  ): Promise<void> {
    // do a quick pre-check for the subdomain name so that we can exit early in the
    //   the "non-race-condition" case.
    const inQueue = await this.isSubdomainInQueue(subdomainName)
 
    Iif (inQueue) {
      logger.warn(`Name queued already: ${subdomainName}`, {
        msgType: 'repeat_name',
        name: subdomainName,
        ip: ipAddress
      })
      throw new Error('Subdomain operation already queued for this name.')
    }
 
    const isValid = await isRegistrationValid(
      subdomainName,
      this.domainName,
      owner,
      sequenceNumber,
      true
    )
 
    if (!isValid) {
      logger.warn(
        `Discarding operation for ${subdomainName} because it failed validation.`
      )
      throw new Error('Requested subdomain operation is invalid.')
    }
 
    const isSpam = await this.spamCheck(
      subdomainName,
      owner,
      zonefile,
      ipAddress,
      authorization
    )
 
    if (isSpam) {
      throw new Error(isSpam)
    }
 
    try {
      await this.lock.acquire(
        QUEUE_LOCK,
        async () => {
          try {
            // check again while holding the QUEUE_LOCK in case we raced.
            if (await this.isSubdomainInQueue(subdomainName)) {
              logger.warn(`Name queued already: ${subdomainName}`, {
                msgType: 'repeat_name',
                name: subdomainName,
                ip: ipAddress
              })
              throw new Error(
                'Subdomain operation already queued for this name.'
              )
            }
            await this.db.addToQueue(
              subdomainName,
              owner,
              sequenceNumber,
              zonefile
            )
            try {
              await this.db.logRequestorData(subdomainName, owner, ipAddress)
            } catch (err) {
              logger.error(`Setting status for ${subdomainName} as errored.`)
              await this.db.updateStatusFor(
                [subdomainName],
                'Error logging ip info',
                ''
              )
              throw err
            }
            logger.info('Queued registration request.', {
              msgType: 'queued',
              name: subdomainName,
              owner,
              ip: ipAddress
            })
          } catch (err) {
            logger.error(`Error processing registration: ${err}`)
            logger.error(err.stack)
            throw err
          }
        },
        { timeout: 5000 }
      )
    } catch (err) {
      Iif (err && err.message && err.message == 'async-lock timed out') {
        logger.error('Failure acquiring registration lock', {
          msgType: 'lock_acquire_fail'
        })
        throw new Error('Failed to obtain lock')
      } else {
        throw err
      }
    }
  }
 
  async getSubdomainStatus(
    subdomainName: string
  ): Promise<{ status: string, statusCode?: number }> {
    if (await isSubdomainRegistered(`${subdomainName}.${this.domainName}`)) {
      return { status: 'Subdomain propagated' }
    } else {
      const rows = await this.db.getStatusRecord(subdomainName)
 
      if (rows.length > 0) {
        const statusRecord = rows[0]
        if (statusRecord.status == 'received') {
          return {
            status:
              'Subdomain is queued for update and should be' +
              ' announced within the next few blocks.'
          }
        } else if (statusRecord.status == 'submitted') {
          return {
            status:
              `Your subdomain was registered in transaction ${statusRecord.status_more}` +
              ' -- it should propagate on the network once it has 6 confirmations.'
          }
        } else {
          return { status: statusRecord.status }
        }
      } else {
        return {
          status: 'Subdomain not registered with this registrar',
          statusCode: 404
        }
      }
    }
  }
 
  async isSubdomainInQueue(subdomainName: string): Promise<boolean> {
    const rows = await this.db.getStatusRecord(subdomainName)
    return rows.length > 0
  }
 
  backupZonefile(zonefile: string) {
    return this.db.backupZonefile(zonefile)
  }
 
  addTransactionToTrack(txHash: string, zonefile: string) {
    return this.db.trackTransaction(txHash, zonefile)
  }
 
  updateQueueStatus(namesSubmitted: Array<string>, txHash: string) {
    return this.db.updateStatusFor(namesSubmitted, 'submitted', txHash)
  }
 
  async markTransactionsComplete(
    entries: Array<{ txHash: string, status: boolean, blockHeight: number }>
  ): Promise<void> {
    if (entries.length > 0) {
      logger.info(`${entries.length} transactions newly finished.`, {
        msgType: 'tx_finish',
        count: entries.length
      })
    } else {
      logger.debug(`${entries.length} transactions newly finished.`)
      return
    }
 
    return await this.db.flushTrackedTransactions(entries)
  }
 
  async submitBatch(): Promise<string> {
    try {
      return await this.lock.acquire(
        QUEUE_LOCK,
        async () => {
          try {
            logger.debug('Obtained lock, fetching queue.')
            const queue: QueueRecord[] = await this.db.fetchQueue()
            const results = await Promise.all(
              queue.map((subdomainOp) =>
                isRegistrationValid(
                  subdomainOp.subdomainName,
                  this.domainName,
                  subdomainOp.owner,
                  parseInt(subdomainOp.sequenceNumber),
                  this.checkCoreOnBatching
                )
              )
            )
            const valid = queue.filter((op, opIndex) => results[opIndex])
            const invalid = queue.filter((op, opIndex) => !results[opIndex])
            invalid.forEach((op) =>
              logger.warn(
                `Skipping registration of ${op.subdomainName} ` +
                  'because it is not valid.',
                { msgType: 'skip_batch_inclusion', name: op.subdomainName }
              )
            )
 
            if (valid.length === 0) {
              logger.debug(`${valid.length} items in the queue.`)
              return null
            }
            if (valid.length < this.minBatchSize) {
              logger.info('Skipping batch because it is too small.', {
                msgType: 'skip_batch',
                currentQueue: valid.length,
                minBatchSize: this.minBatchSize
              })
              return null
            }
 
            logger.info(
              `Constructing batch with ${valid.length} currently queued.`,
              { msgType: 'begin_batch', currentQueue: valid.length }
            )
            const update = makeUpdateZonefile(
              this.domainName,
              this.uriEntries,
              valid,
              this.zonefileSize
            )
            const zonefile = update.zonefile
            const updatedFromQueue = update.submitted
            logger.debug(
              `[${JSON.stringify(updatedFromQueue)}] will be in this batch.`
            )
            logger.info(
              `Batch will contain ${updatedFromQueue.length} entries.`,
              {
                msgType: 'built_batch',
                currentQueue: valid.length,
                batchSize: updatedFromQueue.length
              }
            )
 
            await this.backupZonefile(zonefile)
            const txHash = await submitUpdate(
              this.domainName,
              zonefile,
              this.ownerKey,
              this.paymentKey
            )
            await this.updateQueueStatus(updatedFromQueue, txHash)
            await this.addTransactionToTrack(txHash, zonefile)
            logger.info('Batch submitted', {
              msgType: 'batch_submitted',
              txid: txHash
            })
            return txHash
          } catch (err) {
            logger.error(`Failed to submit batch: ${err}`)
            logger.error(err.stack)
            throw err
          }
        },
        { timeout: 5000 }
      )
    } catch (err) {
      if (err && err.message && err.message == 'async-lock timed out') {
        throw new Error('Failed to obtain lock')
      } else {
        throw err
      }
    }
  }
 
  async getSubdomainInfo(fullyQualifiedName: string) {
    Iif (!fullyQualifiedName.endsWith(`.${this.domainName}`)) {
      return { message: { error: 'Wrong domain' }, statusCode: 400 }
    }
    const namePieces = fullyQualifiedName.split('.')
    Iif (namePieces.length !== 3) {
      return { message: { error: 'Bad name' }, statusCode: 400 }
    }
    const subdomainName = namePieces[0]
    const rows = await this.db.getStatusRecord(subdomainName)
 
    if (rows.length > 0) {
      const statusRecord = rows[0]
      const nameRecord = {
        blockchain: 'stacks',
        status: 'unknown',
        last_txid: '', // eslint-disable-line camelcase
        zonefile: statusRecord.zonefile,
        address: statusRecord.owner,
        zonefile_hash: ''
      } // eslint-disable-line camelcase
      if (statusRecord.status === 'received') {
        nameRecord.status = 'pending_subdomain'
        nameRecord.last_txid = '' // eslint-disable-line camelcase
      } else Eif (statusRecord.status === 'submitted') {
        nameRecord.status = 'submitted_subdomain'
        nameRecord.last_txid = statusRecord.status_more // eslint-disable-line camelcase
      }
      nameRecord.zonefile_hash = hash160(
        // eslint-disable-line camelcase
        Buffer.from(nameRecord.zonefile)
      ).toString('hex')
      return { message: nameRecord, statusCode: 200 }
    } else if (!this.isValidLength(subdomainName)) {
      return { message: { status: 'invalid_name' }, statusCode: 400 }
    } else {
      return { message: { status: 'available' }, statusCode: 404 }
    }
  }
 
  async checkZonefiles() {
    logger.debug('Checking for outstanding transactions.')
    try {
      return await this.lock.acquire(
        QUEUE_LOCK,
        async () => {
          logger.debug('Obtained lock, checking transactions.')
 
          try {
            const entries = await this.db.getTrackedTransactions()
            Eif (entries.length > 0) {
              logger.info(`${entries.length} outstanding transactions.`, {
                msgType: 'outstanding_tx',
                count: entries.length
              })
            } else {
              logger.debug(`${entries.length} outstanding transactions.`)
            }
            const statuses = await checkTransactions(entries)
 
            await this.db.updateTransactionHeights(entries)
 
            const completed = statuses.filter((x) => x.status)
 
            await this.markTransactionsComplete(completed)
            logger.debug('Lock released')
          } catch (err) {
            logger.error(`Failure trying to publish zonefiles: ${err}`)
            logger.error(err.stack)
            throw new Error(`Failed to check transaction status: ${err}`)
          }
        },
        { timeout: 5000 }
      )
    } catch (err) {
      Eif (err && err.message && err.message == 'async-lock timed out') {
        throw new Error('Failed to obtain lock')
      } else {
        throw err
      }
    }
  }
 
  async listSubdomainRecords(page: number) {
    logger.debug(`Listing subdomain page ${page}`)
    const timeLimit = new Date().getTime() / 1000 - TIME_WEEK
 
    const records: SubdomainRecord[] = await this.db.listSubdomains(
      page,
      timeLimit
    )
    const rows: SubdomainResult[] = records.map((row) => {
      const formattedRow = {
        name: `${row.subdomainName}.${this.domainName}`,
        address: row.owner,
        sequence: row.sequenceNumber,
        zonefile: row.zonefile,
        status: row.status,
        iterator: row.queue_ix
      }
      return formattedRow
    })
    return { message: rows, statusCode: 200 }
  }
 
  async validateTransferSubdomain(
    subdomainOp: SubdomainOp,
    newOwner: string,
    signature: string
  ) {
    // owner should be a stacks address
    Iif (!validateStacksAddress(newOwner)) {
      return `'${newOwner}' is not a valid stx address`
    }
 
    const signerAddress = subdomainOp.owner
 
    const newSubdomainOp = {
      ...subdomainOp,
      owner: newOwner,
      sequenceNumber: 1, // seqn is unknown to transfer initiator
      signature: undefined // sig should NOT be included in hash
    }
    const subdomainPieces = subdomainOpToZFPieces(newSubdomainOp)
    const textToSign = subdomainPieces.txt.join(',')
    const hash = crypto.createHash('sha256').update(textToSign).digest('hex')
 
    try {
      const publicKey = {
        data: Buffer.from(publicKeyFromSignature(hash, { data: signature }), 'hex')
      }
      const addressVersion = process.env.BSK_SUBDOMAIN_TESTNET
        ? AddressVersion.TestnetSingleSig
        : AddressVersion.MainnetSingleSig
      const address = publicKeyToAddress(addressVersion, publicKey)
 
      Iif (signerAddress !== address) {
        return `signature error: current owner '${signerAddress}' does not match initiator '${address}'`
      }
    } catch (error) {
      return `signature error: ${newOwner} ${error.message}`
    }
 
    return false
  }
 
  async transferSubdomain(
    requestedSubdomains: {
      subdomainName: string,
      new_owner: string,
      signature: string,
    }[],
    authorization: ?string = '',
    ipAddress: string = ''
  ): Promise<void> {
    Iif (authorization && authorization.startsWith('bearer ')) {
      const apiKey = authorization.slice('bearer '.length)
      if (this.apiKeys.includes(apiKey)) {
        logger.info('Passed spam checks with API key', {
          msgType: 'spam_pass',
          reason: 'api_key',
          apiKey: apiKey.slice(0, 5)
        })
      }
    }
 
    const subdomainRecords: SubdomainOp[] = []
    //extract subdomain from db
    Iif (requestedSubdomains.length === 0) {
      throw new Error('empty subdomains list')
    }
    for (let i = 0; i < requestedSubdomains.length; i++) {
      const subdomainDb = await this.db.getSubdomainRecord(
        requestedSubdomains[i].subdomainName
      )
      const hasErrors = await this.validateTransferSubdomain(
        subdomainDb,
        requestedSubdomains[i].new_owner,
        requestedSubdomains[i].signature
      )
      Iif (hasErrors) {
        throw new Error(hasErrors)
      }
      const newSubdomain = {
        ...subdomainDb,
        owner: requestedSubdomains[i].new_owner,
        signature: requestedSubdomains[i].signature,
        sequenceNumber: 1 // reset seqn for transfer
      }
      subdomainRecords.push(newSubdomain)
    }
 
    const update = makeUpdateZonefile(
      this.domainName,
      this.uriEntries,
      subdomainRecords,
      this.zonefileSize
    )
    const zonefile = update.zonefile
 
    const txHash = await submitUpdate(
      this.domainName,
      update.zonefile,
      this.ownerKey,
      this.paymentKey
    )
 
    //deprecate old subdomain data
    this.db.updateStatusFor(
      subdomainRecords.map((subdomain) => subdomain.subdomainName),
      'transfered',
      'subdomain transfered to a new address'
    )
 
    //make updates for transfer subdomains
    this.db.makeTransferUpdates(subdomainRecords, txHash)
    subdomainRecords.forEach((subdomain) => {
      this.db.logTransferRequestorData(
        subdomain.subdomainName,
        subdomain.owner,
        ipAddress
      )
    })
    this.db.trackTransaction(txHash, zonefile)
    return txHash
  }
 
  shutdown() {
    return this.db.shutdown()
  }
}