All files db.js

87.88% Statements 116/132
55.88% Branches 19/34
93.88% Functions 46/49
89.06% Lines 114/128

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        1x                                           1x                       1x     1x     1x           1x           1x           1x             1x     1x             84x 48x   84x 84x 84x     84x                     95x 16x   95x 95x 95x     95x             6x               6x 6x               6x 6x       6x                             6x               6x 6x     6x 6x         6x       6x 6x 6x 6x 6x 6x   6x 6x   6x 6x   6x 6x   6x 6x 6x     6x         6x 48x                     11x   11x 11x               1x       1x                               1x     1x 1x   1x     1x 1x                     4x 4x 4x   4x               11x     11x 11x   11x 1x   10x 10x           18x 18x 18x         3x 3x 3x           6x               6x 6x 7x             7x           43x   43x         1x       1x   1x     1x                                 2x                     2x         2x 1x                 1x         3x               2x         2x       4x                             2x 2x   2x                       1x 1x 1x   1x 1x 1x         1x 1x 1x     1x     1x        
/* @flow */
 
import sqlite3 from 'sqlite3'
import logger from 'winston'
const path = require('path')
 
// eslint-disable-next-line
export type QueueRecord = {
  subdomainName: string,
  owner: string,
  sequenceNumber: number,
  zonefile: string,
  signature: string,
};
 
// eslint-disable-next-line
export type SubdomainRecord = {
  subdomainName: string,
  owner: string,
  sequenceNumber: number,
  zonefile: string,
  signature: string,
  status: string,
  queue_ix: number,
};
 
const CREATE_QUEUE = `CREATE TABLE subdomain_queue (
 queue_ix INTEGER PRIMARY KEY,
 subdomainName TEXT NOT NULL,
 owner TEXT NOT NULL,
 sequenceNumber TEXT NOT NULL,
 zonefile TEXT NOT NULL,
 signature TEXT DEFAULT NULL,
 status TEXT NOT NULL,
 status_more TEXT,
 received_ts DATETIME DEFAULT CURRENT_TIMESTAMP
);`
 
const CREATE_QUEUE_INDEX = `CREATE INDEX subdomain_queue_index ON
 subdomain_queue (subdomainName);`
 
const CREATE_QUEUE_RECEIVED_INDEX = `CREATE INDEX subdomain_queue_received_index ON
 subdomain_queue (received_ts);`
 
const CREATE_MYZONEFILE_BACKUPS = `CREATE TABLE subdomain_zonefile_backups (
 backup_ix INTEGER PRIMARY KEY,
 zonefile TEXT NOT NULL,
 timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);`
 
const CREATE_TRANSACTIONS_TRACKED = `CREATE TABLE transactions_tracked (
 tracker_ix INTEGER PRIMARY KEY,
 txHash TEXT NOT NULL,
 zonefile TEXT NOT NULL
);`
 
const CREATE_TX_INFO = `CREATE TABLE transactions_info (
 txinfo_ix INTEGER PRIMARY KEY,
 txHash TEXT NOT NULL UNIQUE,
 blockHeight INTEGER DEFAULT 0
);`
 
const CREATE_IP_INFO = `CREATE TABLE ip_info (
 ipinfo_ix INTEGER PRIMARY KEY,
 ip_address TEXT NOT NULL,
 owner TEXT NOT NULL,
 queue_ix INTEGER NOT NULL
);`
 
const CREATE_IP_INFO_INDEX = `CREATE INDEX ip_info_index ON
 ip_info (ip_address);`
 
const SUBDOMAIN_PAGE_SIZE = 100
 
function dbRun(
  db: sqlite3.Database,
  cmd: string,
  args?: Array<Object>
): Promise<void> {
  if (!args) {
    args = []
  }
  return new Promise((resolve, reject) => {
    db.run(cmd, args, (err) => {
      Iif (err) {
        reject(err)
      } else {
        resolve()
      }
    })
  })
}
 
function dbAll(
  db: sqlite3.Database,
  cmd: string,
  args?: Array<Object>
): Promise<Array<Object>> {
  if (!args) {
    args = []
  }
  return new Promise((resolve, reject) => {
    db.all(cmd, args, (err, rows) => {
      Iif (err) {
        reject(err)
      } else {
        resolve(rows)
      }
    })
  })
}
 
function isInMemory(dbPath: string) {
  return dbPath.includes(':memory:')
}
 
export class RegistrarQueueDB {
  dbLocation: string;
  db: sqlite3.Database;
 
  constructor(dbLocation: string) {
    Eif (isInMemory(dbLocation)) {
      this.dbLocation = dbLocation
    } else {
      const dbPath = path.resolve(__dirname, dbLocation)
      this.dbLocation = dbPath
    }
  }
 
  initialize(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.db = new sqlite3.Database(
        this.dbLocation,
        sqlite3.OPEN_READWRITE,
        (errOpen) => {
          Iif (errOpen) {
            logger.warn(`No database found ${this.dbLocation}, creating`)
            this.db = new sqlite3.Database(
              this.dbLocation,
              sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
              (errCreate) => {
                if (errCreate) {
                  reject(`Failed to load database ${this.dbLocation}`)
                } else {
                  logger.warn('Creating tables...')
                  this.checkTablesAndCreate().then(() => resolve())
                }
              }
            )
          } else {
            return this.checkTablesAndCreate().then(() => resolve())
          }
        }
      )
    })
  }
 
  async checkTablesAndCreate(): Promise<void> {
    const needsCreation = await this.tablesExist()
    Iif (needsCreation.length === 0) {
      return
    } else {
      logger.info(`Creating ${needsCreation.length} tables.`)
      await this.createTables(needsCreation)
    }
  }
 
  tablesExist() {
    return dbAll(
      this.db,
      'SELECT name FROM sqlite_master WHERE type = "table"'
    ).then((results) => {
      const tables = results.map((x) => x.name)
      const toCreate = []
      Eif (tables.indexOf('subdomain_queue') < 0) {
        toCreate.push(CREATE_QUEUE)
        toCreate.push(CREATE_QUEUE_INDEX)
        toCreate.push(CREATE_QUEUE_RECEIVED_INDEX)
      }
      Eif (tables.indexOf('subdomain_zonefile_backups') < 0) {
        toCreate.push(CREATE_MYZONEFILE_BACKUPS)
      }
      Eif (tables.indexOf('transactions_tracked') < 0) {
        toCreate.push(CREATE_TRANSACTIONS_TRACKED)
      }
      Eif (tables.indexOf('transactions_info') < 0) {
        toCreate.push(CREATE_TX_INFO)
      }
      Eif (tables.indexOf('ip_info') < 0) {
        toCreate.push(CREATE_IP_INFO)
        toCreate.push(CREATE_IP_INFO_INDEX)
      }
 
      return toCreate
    })
  }
 
  async createTables(toCreate: Array<string>): Promise<void> {
    for (const createCmd of toCreate) {
      await dbRun(this.db, createCmd)
    }
  }
 
  addToQueue(
    subdomainName: string,
    owner: string,
    sequenceNumber: number,
    zonefile: string
  ): Promise<void> {
    const dbCmd =
      'INSERT INTO subdomain_queue ' +
      '(subdomainName, owner, sequenceNumber, zonefile, status) VALUES (?, ?, ?, ?, ?)'
    const dbArgs = [subdomainName, owner, sequenceNumber, zonefile, 'received']
    return dbRun(this.db, dbCmd, dbArgs)
  }
 
  async makeTransferUpdates(
    transferedSubdomains: QueueRecord[],
    txHash: string
  ): Promise<void> {
    const dbCmd =
      'INSERT INTO subdomain_queue ' +
      '(subdomainName, owner, sequenceNumber, zonefile, signature, status, status_more) VALUES ' +
      '(?, ?, ?, ?, ?, ?, ?)'
 
    Promise.all(transferedSubdomains.map((subdomain) => dbRun(this.db, dbCmd, [
      subdomain.subdomainName,
      subdomain.owner,
      subdomain.sequenceNumber,
      subdomain.zonefile,
      subdomain.signature,
      'submitted',
      txHash
    ])))
  }
 
  logTransferRequestorData(
    subdomainName: string,
    ownerAddress: string,
    ipAddress: string
  ) {
    const lookup = `SELECT queue_ix FROM subdomain_queue WHERE subdomainName = ?
                    AND owner = ? AND sequenceNumber = 1`
    const insert =
      'INSERT INTO ip_info (ip_address, owner, queue_ix) VALUES (?, ?, ?)'
    return dbAll(this.db, lookup, [subdomainName, ownerAddress]).then(
      (results) => {
        Iif (results.length != 1) {
          throw new Error('No queued entry found.')
        }
        const queueIndex = results[0].queue_ix
        return dbRun(this.db, insert, [ipAddress, ownerAddress, queueIndex])
      }
    )
  }
 
  async updateStatusFor(
    subdomains: Array<string>,
    status: string,
    statusMore: string
  ): Promise<string> {
    const cmd =
      'UPDATE subdomain_queue SET status = ?, status_more = ? WHERE subdomainName = ?'
    await Promise.all(
      subdomains.map((name) => dbRun(this.db, cmd, [status, statusMore, name]))
    )
    return statusMore
  }
 
  logRequestorData(
    subdomainName: string,
    ownerAddress: string,
    ipAddress: string
  ) {
    const lookup = `SELECT queue_ix FROM subdomain_queue WHERE subdomainName = ?
                    AND owner = ? AND sequenceNumber = 0`
    const insert =
      'INSERT INTO ip_info (ip_address, owner, queue_ix) VALUES (?, ?, ?)'
    return dbAll(this.db, lookup, [subdomainName, ownerAddress]).then(
      (results) => {
        if (results.length != 1) {
          throw new Error('No queued entry found.')
        }
        const queueIndex = results[0].queue_ix
        return dbRun(this.db, insert, [ipAddress, ownerAddress, queueIndex])
      }
    )
  }
 
  getOwnerAddressCount(ownerAddress: string) {
    const lookup = 'SELECT * FROM ip_info WHERE owner = ?'
    return dbAll(this.db, lookup, [ownerAddress]).then(
      (results) => results.length
    )
  }
 
  getIPAddressCount(ipAddress: string) {
    const lookup = 'SELECT * FROM ip_info WHERE ip_address = ?'
    return dbAll(this.db, lookup, [ipAddress]).then(
      (results) => results.length
    )
  }
 
  async fetchQueue(): Promise<QueueRecord[]> {
    const cmd =
      'SELECT subdomainName, owner, sequenceNumber, zonefile, signature' +
      ' FROM subdomain_queue WHERE status = "received"'
    const results: {
      subdomainName: string,
      owner: string,
      sequenceNumber: string,
      zonefile: string,
      signature: string,
    }[] = await dbAll(this.db, cmd)
    return results.map((x) => {
      const out = {
        subdomainName: x.subdomainName,
        owner: x.owner,
        sequenceNumber: parseInt(x.sequenceNumber),
        zonefile: x.zonefile,
        signature: x.signature
      }
      return out
    })
  }
 
  getStatusRecord(subdomainName: string) {
    const lookup =
      'SELECT status, status_more, owner, zonefile FROM subdomain_queue' +
      ' WHERE subdomainName = ? ORDER BY queue_ix DESC LIMIT 1'
    return dbAll(this.db, lookup, [subdomainName])
  }
 
  async getSubdomainRecord(subdomainName: string): Promise<SubdomainRecord> {
    const lookup =
      'SELECT subdomainName, owner, sequenceNumber, zonefile, signature, status, queue_ix' +
      ' FROM subdomain_queue' +
      ' WHERE subdomainName = ? ORDER BY queue_ix DESC LIMIT 1'
 
    const result = await dbAll(this.db, lookup, [subdomainName])
 
    Iif (result.length != 1) {
      throw new Error('no subdomain found')
    }
    return {
      subdomainName: result[0].subdomainName,
      owner: result[0].owner,
      sequenceNumber: parseInt(result[0].sequenceNumber),
      zonefile: result[0].zonefile,
      signature: result[0].signature,
      status: result[0].status,
      queue_ix: result[0].queue_ix
    }
 
  }
 
  async listSubdomains(
    iterator: number,
    timeLimit: number
  ): Promise<SubdomainRecord[]> {
    const listSQL =
      'SELECT subdomainName, owner, sequenceNumber, zonefile, signature, ' +
      'status, queue_ix FROM subdomain_queue WHERE ' +
      'queue_ix >= ? AND received_ts >= DATETIME(?, "unixepoch") ORDER BY queue_ix LIMIT ?'
    const results: {
      subdomainName: string,
      owner: string,
      sequenceNumber: string,
      zonefile: string,
      signature: string,
      status: string,
      queue_ix: number,
    }[] = await dbAll(this.db, listSQL, [
      iterator,
      timeLimit,
      SUBDOMAIN_PAGE_SIZE
    ])
    return results.map((x) => {
      const out = {
        subdomainName: x.subdomainName,
        owner: x.owner,
        sequenceNumber: parseInt(x.sequenceNumber),
        zonefile: x.zonefile,
        signature: x.signature,
        status: x.status,
        queue_ix: x.queue_ix
      }
      return out
    })
  }
 
  backupZonefile(zonefile: string): Promise<void> {
    return dbRun(
      this.db,
      'INSERT INTO subdomain_zonefile_backups (zonefile) VALUES (?)',
      [zonefile]
    )
  }
 
  async trackTransaction(txHash: string, zonefile: string): Promise<string> {
    await dbRun(
      this.db,
      'INSERT INTO transactions_tracked (txHash, zonefile) VALUES (?, ?)',
      [txHash, zonefile]
    )
    return txHash
  }
 
  getTrackedTransactions() {
    return dbAll(
      this.db,
      'SELECT t.txHash, t.zonefile, IFNULL(ti.blockHeight, 0) as blockHeight FROM transactions_tracked as t ' +
        'LEFT JOIN transactions_info as ti ON t.txHash = ti.txHash'
    )
  }
 
  async updateTransactionHeights(
    transactions: Array<{
      txHash: string,
      blockHeight: number,
      status: boolean,
    }>
  ): Promise<void> {
    const cmd =
      'REPLACE INTO transactions_info(txHash, blockHeight) VALUES (?, ?)'
    await Promise.all(
      transactions.map((entry) =>
        dbRun(this.db, cmd, [entry.txHash, entry.blockHeight])
      )
    )
  }
 
  async flushTrackedTransactions(
    transactions: Array<{
      txHash: string,
      blockHeight: number,
      status: boolean,
    }>
  ): Promise<void> {
    let cmd = 'DELETE FROM transactions_tracked WHERE txHash = ?'
    await Promise.all(
      transactions.map((entry) => dbRun(this.db, cmd, [entry.txHash]))
    )
    cmd = 'DELETE FROM transactions_info WHERE txHash = ?'
    await Promise.all(
      transactions.map((entry) => dbRun(this.db, cmd, [entry.txHash]))
    )
  }
 
  shutdown(): Promise<void> {
    return new Promise((resolve, reject) => {
      this.db.close((err) => {
        Iif (err) {
          reject(err)
        } else {
          resolve()
        }
      })
      this.db = undefined
    })
  }
}