buffer#Buffer TypeScript Examples

The following examples show how to use buffer#Buffer. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From netmd-js with GNU General Public License v2.0 7 votes vote down vote up
export function createAeaHeader(name = '', channels = 2, soundgroups = 1, groupstart = 0, encrypted = 0, flags = [0, 0, 0, 0, 0, 0, 0, 0]) {
    const encodedName = Buffer.from(name);
    const header = concatUint8Arrays(
        new Uint8Array(wordToByteArray(2048, 4, true)),
        encodedName,
        new Uint8Array(256 - encodedName.length),
        new Uint8Array(wordToByteArray(soundgroups, 4, true)),
        new Uint8Array([channels, 0]),
        new Uint8Array(wordToByteArray(flags[0], 4, true)),
        new Uint8Array(wordToByteArray(flags[1], 4, true)),
        new Uint8Array(wordToByteArray(flags[2], 4, true)),
        new Uint8Array(wordToByteArray(flags[3], 4, true)),
        new Uint8Array(wordToByteArray(flags[4], 4, true)),
        new Uint8Array(wordToByteArray(flags[5], 4, true)),
        new Uint8Array(wordToByteArray(flags[6], 4, true)),
        new Uint8Array(wordToByteArray(flags[7], 4, true)),
        new Uint8Array(wordToByteArray(0, 4, true)),
        new Uint8Array(wordToByteArray(encrypted, 4, true)),
        new Uint8Array(wordToByteArray(groupstart, 4, true))
    );
    return concatUint8Arrays(header, new Uint8Array(2048 - header.length));
}
Example #2
Source File: utils.ts    From pebula-node with MIT License 7 votes vote down vote up
/**
 * @internal
 * @ignore
 * If you try to turn a Guid into a Buffer in .NET, the bytes of the first three groups get
 * flipped within the group, but the last two groups don't get flipped, so we end up with a
 * different byte order. This is the order of bytes needed to make Service Bus recognize the token.
 *
 * @param lockToken The lock token whose bytes need to be reorded.
 * @returns Buffer - Buffer representing reordered bytes.
 */
export function reorderLockToken(lockTokenBytes: Buffer): Buffer {
  if (!lockTokenBytes || !Buffer.isBuffer(lockTokenBytes)) {
    return lockTokenBytes;
  }

  return Buffer.from([
    lockTokenBytes[3],
    lockTokenBytes[2],
    lockTokenBytes[1],
    lockTokenBytes[0],

    lockTokenBytes[5],
    lockTokenBytes[4],

    lockTokenBytes[7],
    lockTokenBytes[6],

    lockTokenBytes[8],
    lockTokenBytes[9],

    lockTokenBytes[10],
    lockTokenBytes[11],
    lockTokenBytes[12],
    lockTokenBytes[13],
    lockTokenBytes[14],
    lockTokenBytes[15]
  ]);
}
Example #3
Source File: MarginWeb3.ts    From zo-client with Apache License 2.0 6 votes vote down vote up
static async loadFromAccountInfo(
    program: Program<Zo>,
    st: State,
    accountInfo: AccountInfo<Buffer>,
    withOrders: boolean,
  ): Promise<MarginWeb3> {
    const account = program.coder.accounts.decode("margin", accountInfo.data);
    const data = this.transformFetchedData(st, account);
    const control = await Control.load(program, data.control);
    const margin = new this(program, account.publicKey, data, control, st);
    margin.loadBalances();
    margin.loadPositions();
    if (withOrders) {
      await margin.loadOrders();
    }
    return margin;
  }
Example #4
Source File: keccak256.ts    From arbundles with Apache License 2.0 6 votes vote down vote up
function toBuffer(value: any) {
  if (!Buffer.isBuffer(value)) {
    if (Array.isArray(value)) {
      value = Buffer.from(value);
    } else if (typeof value === "string") {
      if (isHexString(value)) {
        value = Buffer.from(padToEven(stripHexPrefix(value)), "hex");
      } else {
        value = Buffer.from(value);
      }
    } else if (typeof value === "number") {
      value = intToBuffer(value);
    } else if (value === null || value === undefined) {
      value = Buffer.allocUnsafe(0);
    } else if (BN.isBN(value)) {
      value = value.toArrayLike(Buffer);
    } else if (value.toArray) {
      // converts a BN to a Buffer
      value = Buffer.from(value.toArray());
    } else {
      throw new Error("invalid type");
    }
  }

  return value;
}
Example #5
Source File: BackendService.ts    From mobile with Apache License 2.0 6 votes vote down vote up
async claimOneTimeCode(oneTimeCode: string): Promise<SubmissionKeySet> {
    const randomBytes = await getRandomBytes(32);
    nacl.setPRNG(buff => {
      buff.set(randomBytes, 0);
    });
    const keyPair = nacl.box.keyPair();

    const keyClaimResponse = await this.keyClaim(oneTimeCode, keyPair);
    if (keyClaimResponse.error) {
      throw new Error(`Code ${keyClaimResponse.error}`);
    }

    const serverPublicKey = Buffer.from(keyClaimResponse.serverPublicKey).toString('base64');
    const clientPrivateKey = Buffer.from(keyPair.secretKey).toString('base64');
    const clientPublicKey = Buffer.from(keyPair.publicKey).toString('base64');

    return {
      serverPublicKey,
      clientPrivateKey,
      clientPublicKey,
    };
  }
Example #6
Source File: bn.ts    From edge-currency-plugins with MIT License 6 votes vote down vote up
/**
 * Instantiate a BigNumber from a "signed magnitude buffer"
 * (a buffer where the most significant bit represents the sign (0 = positive, -1 = negative))
 */
BN.fromSM = function (buf: Buffer, opts: Opts) {
  let ret
  if (buf.length === 0) {
    return BN.fromBuffer(Buffer.from([0]))
  }

  const endian = opts.endian ?? 'big'
  if (endian === 'little') {
    buf = reversebuf(buf)
  }

  if ((buf[0] & 0x80) !== 0) {
    buf[0] = buf[0] & 0x7f
    ret = BN.fromBuffer(buf)
    ret.neg().copy(ret)
  } else {
    ret = BN.fromBuffer(buf)
  }
  return ret
}
Example #7
Source File: createBody.ts    From freedeck-configurator with GNU General Public License v3.0 6 votes vote down vote up
createButtonBody = (buttonPages: IButtonPage[]) => {
  const buttonRowCount = buttonPages.length * buttonPages[0].length;
  const buttonRows = new Buffer(16 * buttonRowCount);
  buttonPages.forEach((buttonPage, pageIndex) => {
    buttonPage.forEach((button, buttonIndex) => {
      const rowOffset = buttonPage.length * 16 * pageIndex + buttonIndex * 16;
      // add 16 if the longpress has any functionality
      const secondaryAddition = (button.secondary.enabled ? 1 : 0) * 16;

      // first 8 primary bytes
      if (button.primary.values.length !== 0) {
        const primaryMode = button.primary.mode + secondaryAddition;
        buttonRows.writeUInt8(primaryMode, rowOffset);
        button.primary.values.forEach((value, index) =>
          buttonRows.writeUInt8(value, rowOffset + index + 1)
        );
      } else {
        buttonRows.writeUInt8(EAction.noop + secondaryAddition, rowOffset);
      }
      // 8 secondary bytes
      if (button.primary.mode === EAction.text) return;
      if (button.secondary.values.length !== 0) {
        const secondaryMode = button.secondary.mode;
        buttonRows.writeUInt8(secondaryMode, rowOffset + 8);
        button.secondary.values.forEach((value, index) =>
          buttonRows.writeUInt8(value, rowOffset + index + 1 + 8)
        );
      } else {
        buttonRows.writeUInt8(EAction.noop + secondaryAddition, rowOffset + 8);
      }
    });
  });
  console.timeEnd("buttons");
  return buttonRows;
}
Example #8
Source File: string.ts    From skynet-js with MIT License 6 votes vote down vote up
/**
 * Converts a UTF-8 string to a uint8 array containing valid UTF-8 bytes.
 *
 * @param str - The string to convert.
 * @returns - The uint8 array.
 * @throws - Will throw if the input is not a string.
 */
export function stringToUint8ArrayUtf8(str: string): Uint8Array {
  validateString("str", str, "parameter");

  return Uint8Array.from(Buffer.from(str, "utf-8"));
}
Example #9
Source File: Image.ts    From Asena with MIT License 6 votes vote down vote up
isValidImage(): Promise<boolean>{
        return new Promise<boolean>(resolve => {
            const q = parse(this.url, true);
            const options = {
                path: q.pathname,
                host: q.hostname,
                port: q.port,
                headers: {
                    'Content-Type': 'arraybuffer',
                    'Range': 'bytes=0-7'
                },
                timeout: 2500
            }

            const request = https.get(options, res => {
                const chunks = []

                res.on('data', data => chunks.push(data))
                res.on('end', () => {
                    const buffer = Buffer.concat(chunks)
                    for(const bytes of MagicBytes){
                        if(bytes.equals(buffer.slice(0, bytes.length))){
                            resolve(true)
                        }
                    }

                    resolve(false)
                })
                res.on('error', () => {
                    resolve(false)
                })
            })

            request.on('timeout', () => {
                request.destroy()
                resolve(false)
            })
        })
    }
Example #10
Source File: engine.ts    From aurora.js with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
// TODO: getUpgradeIndex()
  // TODO: stageUpgrade()
  // TODO: deployUpgrade()

  async deployCode(bytecode: Bytecodeish): Promise<Result<Address, Error>> {
    const args = parseHexString(bytecode);
    const outcome = await this.callMutativeFunction('deploy_code', args);
    return outcome.map(({ output }) => {
      const result = SubmitResult.decode(Buffer.from(output));
      return Address.parse(
        Buffer.from(result.output().unwrap()).toString('hex')
      ).unwrap();
    });
  }
Example #11
Source File: torrent-parser.service.ts    From qbit-matUI with MIT License 6 votes vote down vote up
/** Given a torrent file, parse its contents. */
  public async ParseFile(torrent: FileList): Promise<ParsedTorrent> {

    //@ts-ignore -- ArrayBuffer very much does exist on Files...
    let array_buff = await torrent.arrayBuffer()
    let buff = Buffer.from(array_buff);      // Need to convert to a proper Buffer

    return this.torrent_parser(buff);
  }
Example #12
Source File: BackendService.ts    From mobile with Apache License 2.0 6 votes vote down vote up
async claimOneTimeCode(oneTimeCode: string): Promise<SubmissionKeySet> {
    let randomBytes: Buffer;
    try {
      randomBytes = await getRandomBytes(32);
    } catch (error) {
      captureException('getRandomBytes()', error);
      throw new Error(error);
    }
    nacl.setPRNG(buff => {
      buff.set(randomBytes, 0);
    });
    const keyPair = nacl.box.keyPair();

    const keyClaimResponse = await this.keyClaim(oneTimeCode, keyPair);

    const serverPublicKey = Buffer.from(keyClaimResponse.serverPublicKey).toString('base64');
    const clientPrivateKey = Buffer.from(keyPair.secretKey).toString('base64');
    const clientPublicKey = Buffer.from(keyPair.publicKey).toString('base64');

    return {
      serverPublicKey,
      clientPrivateKey,
      clientPublicKey,
    };
  }
Example #13
Source File: Ghost.ts    From craft-extension-inspirations with MIT License 6 votes vote down vote up
export function mkToken(key: string): string | null {
    const parts = key.split(":");
    if (parts.length !== 2) {
        return null;
    }

    const [id, secret] = parts;

    const token = jwt.sign({}, Buffer.from(secret, 'hex'), {
        keyid: id,
        algorithm: "HS256",
        expiresIn: "5m",
        audience: "/v3/admin/"
    });

    return token;
}
Example #14
Source File: utils.ts    From netmd-js with GNU General Public License v2.0 6 votes vote down vote up
export function decodeFromSJIS(sjisBuffer: Uint8Array) {
    return jconv.decode(Buffer.from(sjisBuffer), 'SJIS');
}
Example #15
Source File: telemetry.ts    From vscode-recall with MIT License 6 votes vote down vote up
constructor(private enabled: boolean) {
    const extensionId = 'frenya.vscode-recall';
    const extension = extensions.getExtension(extensionId)!;
    const extensionVersion = extension.packageJSON.version;

    // following key just allows you to send events to azure insights API
    // so it does not need to be protected
    // but obfuscating anyways - bots scan github for keys, but if you want my key you better work for it, damnit!
    const innocentKitten = Buffer.from(
      'NmE3YmNjOTYtZjVmYi00NDIwLTgyZjktYzRhNDUxNzhiMGE2',
      'base64',
    ).toString();

    this.reporter = new TelemetryReporter(extensionId, extensionVersion, innocentKitten);
    this.resetMeasurements();
  }
Example #16
Source File: ble.ts    From iotc-cpm-sample with MIT License 6 votes vote down vote up
protected getValue(characteristic: Characteristic): number | null {
    if (characteristic.value == null) {
      return null;
    }
    const val = Buffer.from(characteristic.value, 'base64');
    if (val.length === 1) {
      const intval = val.readInt8();
      return intval;
    } else if (val.length === 4) {
      return new DataView(val.buffer).getFloat32(0);
    }
    return +val;
  }
Example #17
Source File: encryption.ts    From ironfish with Mozilla Public License 2.0 6 votes vote down vote up
export function boxMessage(
  plainTextMessage: string,
  sender: PrivateIdentity,
  recipient: Identity,
): { nonce: string; boxedMessage: string } {
  const bytes = tweetnacl.randomBytes(tweetnacl.box.nonceLength)
  return {
    nonce: Buffer.from(bytes).toString('base64'),
    boxedMessage: Buffer.from(
      tweetnacl.box(
        Buffer.from(plainTextMessage, 'utf8'),
        bytes,
        Buffer.from(recipient, 'base64'),
        sender.secretKey,
      ),
    ).toString('base64'),
  }
}
Example #18
Source File: sdk.ts    From kim_web_sdk with Apache License 2.0 6 votes vote down vote up
private send(data: Buffer | Uint8Array): boolean {
        try {
            if (this.conn == null) {
                return false
            }
            this.conn.send(data)
        } catch (error) {
            // handle write error
            this.errorHandler(new Error("write timeout"))
            return false
        }
        return true
    }
Example #19
Source File: pool.ts    From lightning-terminal with MIT License 6 votes vote down vote up
/**
   * call the pool `DepositAccount` RPC and return the response
   */
  async deposit(
    traderKey: string,
    amount: Big,
    feeRateSatPerKw = 253,
  ): Promise<POOL.DepositAccountResponse.AsObject> {
    const req = new POOL.DepositAccountRequest();
    req.setTraderKey(Buffer.from(traderKey, 'hex').toString('base64'));
    req.setAmountSat(amount.toString());
    req.setFeeRateSatPerKw(feeRateSatPerKw.toString());
    const res = await this._grpc.request(Trader.DepositAccount, req, this._meta);
    return res.toObject();
  }
Example #20
Source File: createLendingMarket.ts    From port-sdk with MIT License 6 votes vote down vote up
initLendingMarketInstruction = (
  owner: PublicKey,
  quoteCurrency: Buffer,
  lendingMarket: PublicKey,
  lendingProgramId: PublicKey = PORT_LENDING
): TransactionInstruction => {
  const data = Buffer.alloc(DataLayout.span);
  DataLayout.encode(
    {
      instruction: LendingInstruction.InitLendingMarket,
      owner,
      quoteCurrency,
    },
    data
  );

  const keys = [
    getAccess(lendingMarket, AccessType.WRITE),
    getAccess(SYSVAR_RENT_PUBKEY, AccessType.READ),
    getAccess(TOKEN_PROGRAM_ID, AccessType.READ),
  ];

  return new TransactionInstruction({
    keys,
    programId: lendingProgramId,
    data,
  });
}
Example #21
Source File: market.ts    From serum-ts with Apache License 2.0 6 votes vote down vote up
async findBaseTokenAccountsForOwner(
    connection: Connection,
    ownerAddress: PublicKey,
    includeUnwrappedSol = false,
  ): Promise<Array<{ pubkey: PublicKey; account: AccountInfo<Buffer> }>> {
    if (this.baseMintAddress.equals(WRAPPED_SOL_MINT) && includeUnwrappedSol) {
      const [wrapped, unwrapped] = await Promise.all([
        this.findBaseTokenAccountsForOwner(connection, ownerAddress, false),
        connection.getAccountInfo(ownerAddress),
      ]);
      if (unwrapped !== null) {
        return [{ pubkey: ownerAddress, account: unwrapped }, ...wrapped];
      }
      return wrapped;
    }
    return await this.getTokenAccountsByOwnerForMint(
      connection,
      ownerAddress,
      this.baseMintAddress,
    );
  }
Example #22
Source File: remoteForS3.ts    From remotely-save with Apache License 2.0 6 votes vote down vote up
getObjectBodyToArrayBuffer = async (
  b: Readable | ReadableStream | Blob
) => {
  if (b instanceof Readable) {
    return (await new Promise((resolve, reject) => {
      const chunks: Uint8Array[] = [];
      b.on("data", (chunk) => chunks.push(chunk));
      b.on("error", reject);
      b.on("end", () => resolve(bufferToArrayBuffer(Buffer.concat(chunks))));
    })) as ArrayBuffer;
  } else if (b instanceof ReadableStream) {
    return await new Response(b, {}).arrayBuffer();
  } else if (b instanceof Blob) {
    return await b.arrayBuffer();
  } else {
    throw TypeError(`The type of ${b} is not one of the supported types`);
  }
}
Example #23
Source File: serviceBusMessage.ts    From pebula-node with MIT License 6 votes vote down vote up
/**
   * @property The message identifier is an
   * application-defined value that uniquely identifies the message and its payload. The identifier
   * is a free-form string and can reflect a GUID or an identifier derived from the application
   * context. If enabled, the
   * {@link https://docs.microsoft.com/azure/service-bus-messaging/duplicate-detection duplicate detection}
   * identifies and removes second and further submissions of messages with the same MessageId.
   */
  messageId?: string | number | Buffer;
Example #24
Source File: bigint.ts    From buffer-layout-utils with Apache License 2.0 6 votes vote down vote up
bigInt =
    (length: number) =>
    (property?: string): Layout<bigint> => {
        const layout = blob(length, property);
        const { encode, decode } = encodeDecode(layout);

        const bigIntLayout = layout as Layout<unknown> as Layout<bigint>;

        bigIntLayout.decode = (buffer: Buffer, offset: number) => {
            const src = decode(buffer, offset);
            return toBigIntLE(Buffer.from(src));
        };

        bigIntLayout.encode = (bigInt: bigint, buffer: Buffer, offset: number) => {
            const src = toBufferLE(bigInt, length);
            return encode(src, buffer, offset);
        };

        return bigIntLayout;
    }
Example #25
Source File: expo-mixpanel-analytics.ts    From beancount-mobile with MIT License 6 votes vote down vote up
_pushEvent(event: Record<string, string | Record<string, string>>) {
    const data = {
      event: event.name,
      properties: {
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        ...(event.props || {}),
        ...this.superProps,
      },
    };
    if (this.userId) {
      data.properties.distinct_id = this.userId;
    }
    data.properties.token = this.token;
    data.properties.user_agent = this.userAgent;
    data.properties.app_name = this.appName;
    data.properties.app_id = this.appId;
    data.properties.app_version = this.appVersion;
    data.properties.screen_size = this.screenSize;
    data.properties.client_id = this.clientId;
    data.properties.device_name = this.deviceName;
    if (this.platform) {
      data.properties.platform = this.platform;
    }
    if (this.model) {
      data.properties.model = this.model;
    }
    if (this.osVersion) {
      data.properties.os_version = this.osVersion;
    }

    const buffer = Buffer.from(JSON.stringify(data)).toString("base64");

    return fetch(`${MIXPANEL_API_URL}/track/?data=${buffer}`);
  }
Example #26
Source File: normalize.ts    From js-powergate-client with MIT License 6 votes vote down vote up
async function* browserStreamToIt(stream: ReadableStream<Buffer>) {
  const reader = stream.getReader()

  while (true) {
    const result = await reader.read()

    if (result.done) {
      return
    }

    yield result.value
  }
}
Example #27
Source File: admin.component.ts    From data-annotator-for-machine-learning with Apache License 2.0 6 votes vote down vote up
clickDownload(e) {
    this.showDownloadDatasets = true;
    this.avaService.downloadProject(e.id).subscribe(
      (res) => {
        if (res) {
          this.msg = {
            selectedDownloadFile: e.dataSource,
            latestAnnotationTime: e.updatedDate,
            generateDoneTime: res.updateTime,
            format: res.format,
            downloadUrl: this.env.config.enableAWSS3
              ? new Buffer(res.file, 'base64').toString()
              : res.file,
            datasets: this.datasets,
            id: e.id,
            projectName: e.projectName,
            labelType: e.labelType,
            projectType: e.projectType,
            src: 'admin',
            originalDataSets: res.originalDataSets,
          };
        }
      },
      (error: any) => {
        console.log(error);
        this.loading = false;
      },
    );
  }
Example #28
Source File: shell-session.impl.ts    From dev-manager-desktop with Apache License 2.0 6 votes vote down vote up
listen(event: 'close' | 'data', callback: (...args: any[]) => void): this {
    if (event === 'data') {
      const dataCb = (data: Buffer) => {
        callback(data.toString('utf-8').replace(/\n/g, '\n\r'));
      };
      this.stream.on('data', dataCb);
      this.stream.stderr.on('data', dataCb);
      return this;
    }
    return super.listen(event, callback);
  }
Example #29
Source File: MITMContentReplacerImport.tsx    From yakit with GNU Affero General Public License v3.0 6 votes vote down vote up
MITMContentReplacerExport: React.FC<MITMContentReplacerExportProps> = (props) => {
    const [value, setValue] = useState<Uint8Array>(new Uint8Array)
    const [loading, setLoading] = useState(true)
    useEffect(() => {
        ipcRenderer.invoke("ExportMITMReplacerRules", {}).then((r: { JsonRaw: Uint8Array }) => {
            setValue(r.JsonRaw)
        }).catch(e => {
            failed(`导出失败:${e}`)
        }).finally(() => setTimeout(() => setLoading(false), 300))
    }, [])

    return <AutoCard size={"small"} bordered={false} loading={loading} extra={[
        <Button size={"small"} type={"primary"} onClick={() => {
            saveABSFileToOpen("yakit-mitm-replacer-rules-config.json", value)
        }}>另存为</Button>
    ]}>
        <div style={{height: 530}}>
            <YakEditor type={"json"} value={new Buffer(value).toString()} readOnly={true}/>
        </div>
    </AutoCard>
}