Search code examples
windowsbashshellcurlethereum

CURL - invalid character '\\n' in string literal


So I'm writing a simple bash script which takes plaintext message, converts it to hex and makes a curl call to a geth client that is running on my localhost to sign the data. I was able to convert the plaintext message to hex, however when sending the converted hex variable as input to my CURL command it gives me -

jsonrpc":"2.0","error":{"code":-32600,"message":"invalid character '\n' in string literal"}}

Following is the code -

#!/bin/bash

# grabbing day and month from current date
D=$(date)
DAY=$(date -d "$D" '+%d')
MONTH=$(date -d "$D" '+%m')
YEAR=$(date -d "$D" '+%Y')


echo "Day: $DAY"
echo "Month: $MONTH"
echo "Year: $YEAR"

# prepare todays JSON message for attestation

a="SH_$YEAR$MONTH$DAY"
b="_324019325_1_10_001_00_test"
filename=$a$b
hash="test hash"
addl_data="test data"
tag="test tag"

msg=$filename$tag$addl_data$hash
echo "Prepared Message is - $msg"


msg_hex_wn=$(xxd  -ps <<< "$msg")| tr -d '\040\011\012\015'
echo "Message in hex - $msg_hex_wn"
echo "\n"
echo $(xxd  -ps <<< "$msg")| tr -d '\040\011\012\015'


# Signing the message in hex
curl -X POST localhost:8545  -d "{\"jsonrpc\":\"2.0\",\"method\":\"eth_sign\",\"params\":[\"0x525c846b777d003048dbabd0f2dd677086839812\", \"$(xxd  -ps <<< "$msg")| tr -d '\040\011\012\015'\"],\"id\":5}" 





read

Clearly the $(xxd -ps <<< "$msg") part is to be blamed here which might be having \n and parser is reading it as \n, when I tried with just 0x1234 instead of $(xxd -ps <<< "$msg") I was able to get the response, So what I am looking at here is there a way to clean the hex of newlines and empty spaces from $(xxd -ps <<< "$msg") command ? or is there better way to get convert string to hex ?


Solution

  • Your concrete problem is that you are putting the pipeline to tr outside of the command substitution. The | tr yada yada needs to go inside the $(xxd ...) closing parenthesis.

    Capturing the final value into a variable and interpolating it into the curl command line probably simplifies troubleshooting significantly.

    In terms of other ways to do this, I would perhaps go with a simple one-liner

    perl -pe 's/(.)/ sprintf("%02X", ord($1)) //ge' <<<"$msg"