Example #1
0
  /**
   * Copys the code of an account to memory.
   * @param {integer} addressOffset the memory offset of the address
   * @param {integer} resultOffset the memory offset
   * @param {integer} codeOffset the code offset
   * @param {integer} length the length of code to copy
   */
  externalCodeCopy (addressOffset, resultOffset, codeOffset, length, cbIndex) {
    log.debug('EVMImports.js externalCodeCopy')
    this.takeGas(20 + Math.ceil(length / 32) * 3)

    const address = this.getMemory(addressOffset, ADDRESS_SIZE_BYTES)
    const addressHex = '0x' + Buffer.from(address).toString('hex')

    let addressCode = Buffer.from([])

    if (length) {
      if (this.kernel.environment.state[addressHex]) {
        const hexCode = this.kernel.environment.state[addressHex].code.slice(2)
        addressCode = Buffer.from(hexCode, 'hex')
      }
    }

    let opPromise = Promise.resolve(addressCode)

    // wait for all the prevouse async ops to finish before running the callback
    this.kernel.pushOpsQueue(opPromise, cbIndex, code => {
      if (code.length) {
        code = code.slice(codeOffset, codeOffset + length)
        this.setMemory(resultOffset, length, code)
      }
    })
  }
Example #2
0
  /**
   * Creates a new log in the current environment
   * @param {integer} dataOffset the offset in memory to load the memory
   * @param {integer} length the data length
   * @param {integer} number of topics
   */
  log (dataOffset, length, numberOfTopics, topic1, topic2, topic3, topic4) {
    log.debug('EVMImports.js log')
    if (numberOfTopics < 0 || numberOfTopics > 4) {
      throw new Error('Invalid numberOfTopics')
    }

    this.takeGas(375 + length * 8 + numberOfTopics * 375)

    const data = length ? this.getMemory(dataOffset, length).slice(0) : new Uint8Array([])
    const topics = []

    if (numberOfTopics > 0) {
      topics.push(U256.fromMemory(this.getMemory(topic1, U256_SIZE_BYTES)))
    }

    if (numberOfTopics > 1) {
      topics.push(U256.fromMemory(this.getMemory(topic2, U256_SIZE_BYTES)))
    }

    if (numberOfTopics > 2) {
      topics.push(U256.fromMemory(this.getMemory(topic3, U256_SIZE_BYTES)))
    }

    if (numberOfTopics > 3) {
      topics.push(U256.fromMemory(this.getMemory(topic4, U256_SIZE_BYTES)))
    }

    this.kernel.environment.logs.push({
      data: data,
      topics: topics
    })
  }
Example #3
0
  onSocketDisconnect() {
    log.debug('NetworkClient#onSocketDisconnect');

    this.connected = false;

    this.emit('disconnect');
  }
Example #4
0
  /**
   * Copys the code running in current environment to memory.
   * @param {integer} offset the memory offset
   * @param {integer} codeOffset the code offset
   * @param {integer} length the length of code to copy
   */
  codeCopy (resultOffset, codeOffset, length, cbIndex) {
    log.debug('EVMimports.js codeCopy')
    this.takeGas(3 + Math.ceil(length / 32) * 3)

    const contextAccount = this.kernel.environment.address
    let addressCode = Buffer.from([])
    let codeCopied = Buffer.from([])

    if (length) {
      if (this.kernel.environment.state[contextAccount]) {
        const hexCode = this.kernel.environment.state[contextAccount].code.slice(2)
        addressCode = Buffer.from(hexCode, 'hex')
        codeCopied = addressCode.slice(codeOffset, codeOffset + length)
      }
    }

    const opPromise = Promise.resolve(codeCopied)

    // wait for all the prevouse async ops to finish before running the callback
    this.kernel.pushOpsQueue(opPromise, cbIndex, code => {
      if (code.length) {
        this.setMemory(resultOffset, length, code)
      }
    })
  }
Example #5
0
  onSocketConnect() {
    log.debug('NetworkClient#onSocketConnect');

    this.connected = true;

    this.emit('connect');
  }
Example #6
0
  /**
   * store a value at a given path in long term storage which are both loaded
   * from Memory
   * @param {interger} keyOffest the memory offset of the storage key
   * @param {interger} valueOffset the memory offset of the storage value
   */
  storageStore (keyOffset, valueOffset, cbIndex) {
    log.debug('EVMimports.js storageStore')
    this.takeGas(5000)

    const key = this.getMemory(keyOffset, U256_SIZE_BYTES)
    const keyHex = U256.fromMemory(key).toString(16)

    const value = this.getMemory(valueOffset, U256_SIZE_BYTES).slice(0)
    const valueHex = U256.fromMemory(value).toString(16)
    const valIsZero = value.every((i) => i === 0)

    const contextAccount = this.kernel.environment.address
    const oldStorageVal = this.kernel.environment.state[contextAccount]['storage'][keyHex]
    const opPromise = Promise.resolve(oldStorageVal)

    this.kernel.pushOpsQueue(opPromise, cbIndex, oldValue => {
      if (valIsZero && oldValue) {
        // delete a value
        this.kernel.environment.gasRefund += 15000
        delete this.kernel.environment.state[contextAccount]['storage'][keyHex]
      } else {
        if (!valIsZero && !oldValue) {
          // creating a new value
          this.takeGas(15000)
        }
        // update
        this.kernel.environment.state[contextAccount]['storage'][keyHex] = valueHex
      }
    })
  }
Example #7
0
 repo.commit(event.commit_id, function (err, commit) {
     log.debug('Response received for one of issue ' + issue.number + '\'s event commits');
     if (err != null) {
         reject(err);
     }
     event.commit = commit;
     resolve()
 });
 .then((permission) => {
   log.debug("Sending player Id and registrationId back to host page");
   var creator = opener || parent;
   OneSignal.popupPostmam.postMessage(OneSignal.POSTMAM_COMMANDS.REMOTE_NOTIFICATION_PERMISSION_CHANGED, permission);
   OneSignal.popupPostmam.postMessage(OneSignal.POSTMAM_COMMANDS.POPUP_IDS_AVAILBLE)
   if (opener)
     window.close();
 })
Example #9
0
                  copyDocFile('Windows10-next-steps.md', platformDir, function (err) {
                    if (err) {
                      log.error('WARNING: Failed to copy documentation file to the Web platform folder.');
                      log.debug(err);
                    }

                    return task.resolve();
                  });
Example #10
0
      return function (err) {
        if (err) {
          log.warn('WARNING: Failed to download icon file: ' + iconUrl + ' (' + err.message + ')');
          log.debug(err);
        }

        downloadTask.resolve();
      };
Example #11
0
	var reload = function(data){
		if(typeof data === 'undefined'){
			log.debug(chalk.yellow('nothing to reload, quit'));
			return;
		}

		if(this.options.debug){
			log.debug(chalk.green("reloading data:"));
			log.debug(JSON.stringify(data));
			log.debug(chalk.yellow("destroying server..."));
		}

		this.kill(function(){
			log.debug(chalk.yellow("server destroyed"));
		});
		start(data);
	}.bind(this);
Example #12
0
export function checkForUpdates () {
  // dont overlap
  if (updaterState != UPDATER_STATUS_IDLE)
    return

  // track result states for this run
  var isBrowserChecking = false // still checking?
  var isBrowserUpdated = false  // got an update?

  // update global state
  log.debug('[AUTO-UPDATE] Checking for a new version.')
  updaterError = false
  setUpdaterState(UPDATER_STATUS_CHECKING)

  if (isBrowserUpdatesSupported) {
    // check the browser auto-updater
    // - because we need to merge the electron auto-updater, and the npm plugin flow...
    //   ... it's best to set the result events here
    //   (see note above -- back when there WAS a plugin updater, this made since -prf)
    isBrowserChecking = true
    autoUpdater.checkForUpdates()
    autoUpdater.once('update-not-available', () => {
      log.debug('[AUTO-UPDATE] No browser update available.')
      isBrowserChecking = false
      checkDone()
    })
    autoUpdater.once('update-downloaded', () => {
      log.debug('[AUTO-UPDATE] New browser version downloaded. Ready to install.')
      isBrowserChecking = false
      isBrowserUpdated = true
      checkDone()
    })

    // cleanup
    autoUpdater.once('update-not-available', removeAutoUpdaterListeners)
    autoUpdater.once('update-downloaded', removeAutoUpdaterListeners)
    function removeAutoUpdaterListeners () {
      autoUpdater.removeAllListeners('update-not-available')
      autoUpdater.removeAllListeners('update-downloaded')
    }
  }

  // check the result states and emit accordingly
  function checkDone () {
    if (isBrowserChecking)
      return // still checking

    // done, emit based on result
    if (isBrowserUpdated) {
      setUpdaterState(UPDATER_STATUS_DOWNLOADED)
    } else {
      setUpdaterState(UPDATER_STATUS_IDLE)
    }
  }

  // just return a resolve; results will be emitted
  return Promise.resolve()
}
Example #13
0
  render () {
    const {
      isLoading,
      loadingMessage,
      network,
      isMouseUser,
      provider,
      frequentRpcList,
      currentView,
      setMouseUserState,
    } = this.props
    const isLoadingNetwork = network === 'loading' && currentView.name !== 'config'
    const loadMessage = loadingMessage || isLoadingNetwork ?
      this.getConnectingLabel(loadingMessage) : null
    log.debug('Main ui render function')

    return (
      h('.flex-column.full-height', {
        className: classnames({ 'mouse-user-styles': isMouseUser }),
        style: {
          overflowX: 'hidden',
          position: 'relative',
          alignItems: 'center',
        },
        tabIndex: '0',
        onClick: () => setMouseUserState(true),
        onKeyDown: (e) => {
          if (e.keyCode === 9) {
            setMouseUserState(false)
          }
        },
      }, [

        // global modal
        h(Modal, {}, []),

        h(AppHeader),

        // sidebar
        this.renderSidebar(),

        // network dropdown
        h(NetworkDropdown, {
          provider,
          frequentRpcList,
        }, []),

        h(AccountMenu),

        (isLoading || isLoadingNetwork) && h(Loading, {
          loadingMessage: loadMessage,
        }),

        // content
        this.renderRoutes(),
      ])
    )
  }
Example #14
0
    function extenderCallback() {
        var currentTime = self.audioContext.currentTime;
        var endTime = currentTime + 1 / Config.NOMINAL_REFRESH_RATE;
        var eventLen = self.eventPeriod.value;

        while ( lastEventReleaseTime_ < endTime || lastEventTime_ + eventLen < endTime ) {
            // This sligthly fiddly expression allows us to generate the next event earlier than the originally
            // scheduled release time of the previous event, but not later. This is crucial, as we never want
            // the event to run beyond the end of the available audio.
            var eventTime = Math.max( currentTime, Math.min( lastEventReleaseTime_, lastEventTime_ + eventLen ) );

            // Specify the playback speed (which depends on the pitch shift)
            var playSpeed = Converter.semitonesToRatio( self.pitchShift.value );

            // If the event length plus crossface exceeds the available audio duration
            // (taking pitch shift into account), scale both so we don't exceed the
            // available audio.
            // Never use more than this fraction of the audio for a single event

            var xFadeFrac = self.crossFadeDuration.value;
            var audioDur = sourceBuffer_.duration;
            var fadeDur = eventLen * xFadeFrac;
            var requiredDur = playSpeed * ( eventLen + fadeDur );

            if ( requiredDur > MAX_USE * audioDur ) {
                var scale = MAX_USE * audioDur / requiredDur;
                eventLen *= scale;
                fadeDur *= scale;
            }
            requiredDur = playSpeed * ( eventLen + fadeDur );

            // Find a suitable start point as a offset taking into account the required amount of audio
            var startOffset = Math.max( 0, audioDur - requiredDur ) * Math.random();

            log.debug( "Start Point : " + startOffset + " playSpeed : " + playSpeed + " fadeDur : " + fadeDur + " audioDur : " + audioDur + " eventTime : " + eventTime + " eventLen : " + eventLen );

            //  Stop/release the *previous* audio snippet
            if ( lastEventID_ > 0 ) {
                soundQueue_.queueRelease( eventTime, lastEventID_, releaseDur_ );
            }
            // Queue up an event to specify all the properties
            soundQueue_.queueSetSource( eventTime, currentEventID_, sourceBuffer_ );
            soundQueue_.queueSetParameter( eventTime, currentEventID_, 'playSpeed', playSpeed );
            //  Queue the start of the audio snippet
            soundQueue_.queueStart( eventTime, currentEventID_, startOffset, fadeDur );

            releaseDur_ = fadeDur;
            lastEventTime_ = eventTime;
            lastEventReleaseTime_ = eventTime + eventLen;
            lastEventID_ = currentEventID_;
            ++currentEventID_;
        }

        // Keep making callback request if source is still playing.
        if ( self.isPlaying ) {
            window.requestAnimationFrame( extenderCallback );
        }
    }
Example #15
0
	var parseLayers = function() {
		var layers = {},
			layerName,
			layer = {};

		log.debug('Layer {');
		curr = scanner.next();
		while(!groupIs(0, 'ENDTAB')) {

			switch(curr.code) {
				case 2: // layer name
					layer.name = curr.value;
					layerName = curr.value;
					curr = scanner.next();
					break;
				case 62: // color, visibility
					layer.visible = curr.value <= 0;
					// TODO 0 and 256 are BYBLOCK and BYLAYER respectively. Need to handle these values for layers?.
					layer.color = getAcadColor(Math.abs(curr.value));
					curr = scanner.next();
					break;
				case 0:
					// New Layer
					if(curr.value === 'LAYER') {
						log.debug('}');
						layers[layerName] = layer;
						log.debug('Layer {');
						layer = {};
						layerName = undefined;
						curr = scanner.next();
					}
					break;
				default:
					logUnhandledGroup(curr);
					curr = scanner.next();
					break;
			}
		}
		// Note: do not call scanner.next() here,
		//  parseLayerTable() needs the current group
		log.debug('}');
		layers[layerName] = layer;

		return layers;
	};
Example #16
0
 socket.on('close', err => {
   handler.logout()
   socket.destroy()
   if(err){
     log.error(socketLog(socket,'socket closed due to error'))
   } else {
     log.debug(socketLog(socket,'socket closed'))
   }
 })
Example #17
0
      return function (err) {
        if (err) {
          log.warn('WARNING: Failed to create icon folder (' + err.message + ')');
          log.debug(err);
          return task.reject(new Error('Failed to create icon folder'));
        }

        downloader.downloadImage(iconUrl, iconFilePath, createDownloaderImageCallback(downloadTask, iconUrl));
      };
Example #18
0
                    }, function (err, issuesPage) {
                        if (err != null) {
                            reject(err);
                        }
                        log.debug('Issues received: (' + issuesPage.length + ')');

                        receivedIssues = receivedIssues.concat(issuesPage);
                        resolve();
                    });
Example #19
0
  _ensureConnect(method, fn) {
    log.debug('NetworkClient#_ensureConnect', method);

    if (this.connected) {
      fn();
    } else {
      this[method]('connect', fn);
    }
  }
Example #20
0
    function (err) {
    if (err) {
      log.warn('WARNING: Failed replace values of package.appxmanifest');
      log.debug(err);
      return callback(err);
    }

    callback();
  });
Example #21
0
  /**
   * Copys the input data in current environment to memory. This pertains to
   * the input data passed with the message call instruction or transaction.
   * @param {integer} offset the offset in memory to load into
   * @param {integer} dataOffset the offset in the input data
   * @param {integer} length the length of data to copy
   */
  callDataCopy (offset, dataOffset, length) {
    log.debug('EVMImports.js callDataCopy')
    this.takeGas(3 + Math.ceil(length / 32) * 3)

    if (length) {
      const callData = this.kernel.environment.callData.slice(dataOffset, dataOffset + length)
      this.setMemory(offset, length, callData)
    }
  }
Example #22
0
 return (dispatch) => {
   dispatch(actions.showLoadingIndication())
   log.debug(`background.addNewKeyring`)
   background.addNewKeyring(type, opts, (err) => {
     dispatch(actions.hideLoadingIndication())
     if (err) return dispatch(actions.displayWarning(err.message))
     dispatch(actions.showAccountsPage())
   })
 }
Example #23
0
 shapeShiftRequest('shift', { method: 'POST', data}, (response) => {
   dispatch(actions.hideLoadingIndication())
   if (response.error) return dispatch(actions.displayWarning(response.error))
   var message = `
     Deposit your ${response.depositType} to the address below:`
   log.debug(`background.createShapeShiftTx`)
   background.createShapeShiftTx(response.deposit, response.depositType)
   dispatch(actions.showQrView(response.deposit, [message].concat(marketData)))
 })
Example #24
0
  /**
   * Gets the size of code running in current environment.
   * @return {interger}
   */
  getCodeSize (cbIndex) {
    log.debug('EVMImports.js getCodeSize')
    this.takeGas(2)

    const opPromise = Promise.resolve(this.kernel.environment.code.length)

    // wait for all the prevouse async ops to finish before running the callback
    this.kernel.pushOpsQueue(opPromise, cbIndex, length => length)
  }
Example #25
0
 getFeedPage(page).then(result => {
   log.debug(result);
   if (result.isRight()) {
     dispatch(feedPageLoaded(result.right()));
   } else {
     dispatch(errorFetchingPage(result.left()));
   }
   return result;
 });
var serveDocument = function (req, res, next) {
  if (req.path === '/token') {
    return next();
  } else {
    // path is a document name
    log.debug('Serving index.html');
    res.sendFile(path.join(__dirname, '..', 'client', 'index.html'));
  }
};
Example #27
0
  handleAction(action) {
    invariant(action.actionType !== undefined,
      'Actions should contain an actionType when dispatched'
    );

    Log.debug('ACTION:', action);

    this.dispatch(action);
  }
Example #28
0
function WebAudioDispatch( functionCall, time, audioContext ) {
    if ( !audioContext ) {
        log.error( "No AudioContext provided" );
        return;
    }
    var currentTime = audioContext.currentTime;
    // Dispatch anything that's scheduled for anything before current time, current time and the next 5 msecs
    if ( currentTime >= time || time - currentTime < 0.005 ) {
        log.debug( "Dispatching now" );
        functionCall();
    } else {
        log.debug( "Dispatching in", ( time - currentTime ) * 1000, 'ms' );
        window.setTimeout( function () {
            log.debug( "Diff at dispatch", ( time - audioContext.currentTime ) * 1000, 'ms' );
            functionCall();
        }, ( time - currentTime ) * 1000 );
    }
}
Example #29
0
  set curve (points = []) {
    log.debug('Envelope set curve', points)
    const { when } = this.options

    points.forEach((p) => {
      this.gain.linearRampToValueAtTime(p.value, when + p.when)
    })
    this._curve = points
  }
Example #30
0
  /**
   * Triggers the specified event with optional custom data.
   * @param eventName The string event name to be emitted.
   * @param data Any JavaScript variable to be passed with the event.
   * @param remoteTriggerEnv If this method is being called in a different environment (e.g. was triggered in iFrame but now retriggered on main host), this is the string of the original environment for logging purposes.
   */
  static trigger(eventName, data, remoteTriggerEnv=null) {
    if (!contains(SILENT_EVENTS, eventName)) {
      let displayData = data;
      if (remoteTriggerEnv) {
        var env = `${Environment.getEnv().capitalize()} ⬸ ${remoteTriggerEnv.capitalize()}`;
      } else {
        var env = Environment.getEnv().capitalize();
      }

      if (displayData || displayData === false) {
        log.debug(`(${env}) » %c${eventName}:`, getConsoleStyle('event'), displayData);
      } else {
        log.debug(`(${env}) » %c${eventName}`, getConsoleStyle('event'));
      }
    }

    // Actually fire the event that can be listened to via OneSignal.on()
    if (Environment.isBrowser()) {
      if (eventName === OneSignal.EVENTS.SDK_INITIALIZED) {
        if (OneSignal.initialized)
          return;
        else
          OneSignal.initialized = true;
      }
      OneSignal.emit(eventName, data);
    }
    if (LEGACY_EVENT_MAP.hasOwnProperty(eventName)) {
      let legacyEventName = LEGACY_EVENT_MAP[eventName];
      Event._triggerLegacy(legacyEventName, data);
    }

    // If this event was triggered in an iFrame or Popup environment, also trigger it on the host page
    if (!Environment.isHost() && Environment.isBrowser()) {
      var creator = opener || parent;
      if (!creator) {
        log.error(`Could not send event '${eventName}' back to host page because no creator (opener or parent) found!`);
      } else {
        // But only if the event matches certain events
        if (contains(RETRIGGER_REMOTE_EVENTS, eventName)) {
          OneSignal.iframePostmam.message(OneSignal.POSTMAM_COMMANDS.REMOTE_RETRIGGER_EVENT, {eventName: eventName, eventData: data});
        }
      }
    }
  }