Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DRAFT: Offline Token Money - 2 #158

Draft
wants to merge 135 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
135 commits
Select commit Hold shift + click to select a range
0b638b8
Transition between fragment detoks and offline fragment
Ne184 Mar 11, 2023
9badb96
new coin where we can add our work on
alikahawa Mar 12, 2023
b0cdb2e
Added QRCode Scanner
Ne184 Mar 11, 2023
3387dd4
Update QRCode Scanner
VyshnaviMN Mar 12, 2023
0465de8
Add scanner
Ne184 Mar 15, 2023
acb6eea
Added eurotoken
Ne184 Mar 15, 2023
f25d556
Merge branch 'master' into QRcode+scanner
Ne184 Mar 15, 2023
baa06dd
Merge branch 'add-new-coin' into QRcode+scanner
Ne184 Mar 15, 2023
4a29ab5
Added hardcoded list of friends + adding new block function
Ne184 Mar 16, 2023
f822404
move newcoin files in package
Ne184 Mar 16, 2023
dfa6578
UI update
VyshnaviMN Mar 17, 2023
aa3a496
Merge branch 'QRcode+scanner' of https://github.com/Ne184/trustchain-…
VyshnaviMN Mar 17, 2023
50aa72f
wallet uses ipv8 keys, encoding of token as well
Ne184 Mar 17, 2023
10979e9
Adding friend page
Ne184 Mar 17, 2023
8a0bae8
Add show QR code of public key and read results
Ne184 Mar 17, 2023
dff6885
Latest QRCode update
VyshnaviMN Mar 17, 2023
1fe576a
added the wallet interface and create a coin
alikahawa Mar 19, 2023
e63e960
Added Database to store list of friends
VyshnaviMN Mar 20, 2023
c70ebe4
Added simple table for token and functions for reading/saving and del…
Ne184 Mar 24, 2023
672debc
Merge branch 'wallet-interface-create-coin' into QRcode+scanner
Ne184 Mar 26, 2023
6672720
create singleton instance for Wallet
Ne184 Mar 26, 2023
8313932
commented wrong line
Ne184 Mar 26, 2023
8c895c6
Admin page added to UI
Mar 26, 2023
b74b10a
Added tokens to db and remove them upon transfer
alikahawa Mar 26, 2023
8a5f4a2
format some files
alikahawa Mar 26, 2023
455263b
Fixed errors
Ne184 Mar 26, 2023
3c744c3
Changed Public Key to ByteArray
VyshnaviMN Mar 27, 2023
fee9871
Minor fixes, sql table gives error for now commented
Ne184 Mar 27, 2023
983b4f8
fixed small issues
Ne184 Mar 27, 2023
5851f49
Adminfragment
Mar 28, 2023
4b3eaea
Merge branch 'QRcode+scanner' into admin_page
Mar 28, 2023
4b5bbe4
tokenitem
Mar 28, 2023
e6dbfb9
enhanced flow
Mar 28, 2023
8d67a8e
Enhanced item token
julio1998 Mar 28, 2023
8a2bd1c
Created function that connects button to item
julio1998 Mar 29, 2023
fb8ebec
Created separate functions for verification and reissue
julio1998 Mar 29, 2023
dacb1ba
Only admin can do verification and reissue
julio1998 Mar 29, 2023
435807b
Reissued complete
julio1998 Mar 29, 2023
e471b05
Add Admin wallet
julio1998 Mar 29, 2023
ff3e16f
Added requiresapi add correct places
julio1998 Mar 29, 2023
a046d01
style: surpress warning for unused parameters
dsluijk Mar 29, 2023
5e46a64
chore(gossipML): bump cmake version
dsluijk Mar 29, 2023
03b84f8
Merge branch 'admin_page' of github.com:Ne184/trustchain-superapp int…
dsluijk Mar 29, 2023
8036a2d
fix cmake error
julio1998 Mar 29, 2023
c39ea9c
Item list should work (can't verify yet)
julio1998 Mar 29, 2023
4b4cf7c
Should work for admin and user
julio1998 Mar 29, 2023
174f96c
Update add friend, tested
Ne184 Mar 29, 2023
d09d528
Addition of friend is done through the wallet
Ne184 Mar 30, 2023
a1f6a8a
changed to save friends objects, not only usernames
Ne184 Mar 30, 2023
14b69ea
added the function for getting friends public key
Ne184 Apr 1, 2023
5cfa50c
Change wallet class from data object to normal object
Ne184 Apr 1, 2023
8857721
Create first recipients pair, otherwise recipients throws an error
Ne184 Apr 1, 2023
7f59495
Clean logs
Ne184 Apr 1, 2023
64ff9c4
Added token table and removal and addition of tokens
Ne184 Apr 1, 2023
5efeb13
Added function to retrieve all tokens from db and corrected getPayment
Ne184 Apr 1, 2023
f505b34
Merge branch 'database-test' into admin_page
julio1998 Apr 2, 2023
db9f46b
Fixed errors
julio1998 Apr 2, 2023
8b3df51
UI Update
VyshnaviMN Apr 2, 2023
1c5d28e
Fix wrongly formatted tokens
Ne184 Apr 3, 2023
0191160
small changed for showing the list, but it does not show yet
Ne184 Apr 3, 2023
e161a5a
Display tokens in list
julio1998 Apr 8, 2023
96c0c6c
Merge remote-tracking branch 'upstream/admin_page' into admin_page
julio1998 Apr 8, 2023
b04ec9a
Add adminwallet and create tokens in admin screen
julio1998 Apr 10, 2023
a7cde3f
See admin wallet for admin
julio1998 Apr 14, 2023
9a7f90e
Fix unwanted changes
julio1998 Apr 14, 2023
37f8eca
Restore files
julio1998 Apr 14, 2023
c59cd20
Remove unwanted files
julio1998 Apr 14, 2023
e274f7d
Added verification and make button text visible
Ne184 Apr 15, 2023
296bd1e
Fixed comments in PR
julio1998 Apr 15, 2023
69a625b
Merge pull request #13 from Ne184/admin_page
julio1998 Apr 16, 2023
6e3e77a
the translation from the string to the array not working
Ne184 Apr 16, 2023
50d25bb
Updated balance on all pages
VyshnaviMN Apr 16, 2023
f354fd2
Merge branch 'admin_page' into issues-verification-and-testing
VyshnaviMN Apr 16, 2023
0c2b99e
Revert "Merge branch 'admin_page' into issues-verification-and-testing"
VyshnaviMN Apr 16, 2023
f6ba916
started with showing the list of recipients
alikahawa Apr 16, 2023
0b608e5
Revert "started with showing the list of recipients"
alikahawa Apr 16, 2023
5484813
Fix transfer of token (only 1 token can be sent rn))
Ne184 Apr 18, 2023
0a3d4ed
fix transfer of public key, same logic as for token
Ne184 Apr 18, 2023
5eb5cb1
fix: remove of token
Ne184 Apr 18, 2023
99ce43f
Merge branch 'displayCoins' into merge-testingTransfer-expiredToken
Ne184 Apr 18, 2023
2df51f6
update balance
VyshnaviMN Apr 18, 2023
f6f5eac
Combine both methods
Ne184 Apr 19, 2023
531cd67
Update WalletFragment.kt
VyshnaviMN Apr 19, 2023
ae0146a
added timestamp to db
Ne184 Apr 19, 2023
c1dc042
delete comments
Ne184 Apr 19, 2023
544a3e9
Is not tested, will be done on separately
Ne184 Apr 20, 2023
30372c6
added balance to be updated when a coin is added the wallet
Ne184 Apr 20, 2023
191f42a
Merge branch 'add-timestamp-db' into merge-testingTransfer-expiredToken
VyshnaviMN Apr 20, 2023
fa2cab4
Update README.md
VyshnaviMN Apr 21, 2023
7c6df4a
Added double spending prevention
Ne184 Apr 21, 2023
a02d55e
remove verify and history buttons ( not implemented)
Ne184 Apr 21, 2023
b7b0b83
Merge branch 'master' into verification-chain
Ne184 Apr 21, 2023
989ddf3
Update README.md
VyshnaviMN Apr 21, 2023
c55359e
Merge branch 'verification-chain' into merge-testingTransfer-expiredT…
Ne184 Apr 21, 2023
d9af565
Update README.md
VyshnaviMN Apr 21, 2023
1cf9e84
Update README.md
VyshnaviMN Apr 21, 2023
ff4c4b9
Update README.md
Ne184 Apr 25, 2023
511eeb4
Merge pull request #16 from Ne184/merge-testingTransfer-expiredToken
Ne184 Apr 25, 2023
2e54f51
fix changes done by the merge
Ne184 Apr 25, 2023
f273384
fix the show-up of timestamp
Ne184 Apr 25, 2023
c8f4675
Send more tokens
Ne184 Apr 25, 2023
86f2fb8
delete not used files, plus refactor a little bit the ui for admin
Ne184 Apr 25, 2023
0f1e3c1
Update wallet_fragment.xml
Ne184 Apr 25, 2023
5af7e28
denominations backend
Ne184 Apr 27, 2023
172bb9e
Denomination ui updates
VyshnaviMN Apr 27, 2023
4eeac77
fixed the payment method
Ne184 Apr 27, 2023
3a5c715
fixed dropdown
VyshnaviMN Apr 27, 2023
d72d4da
Merge branch 'ui-small-changes' into new-ui-changes
VyshnaviMN Apr 27, 2023
f7739ce
small update
VyshnaviMN Apr 27, 2023
7450ccf
Update denominations balance
VyshnaviMN Apr 27, 2023
39d250e
Dropdown fixed
VyshnaviMN Apr 27, 2023
86ea177
Ad friend fragment
VyshnaviMN Apr 27, 2023
357f65b
fixed field of item, added dropdown to admin
Ne184 Apr 27, 2023
2c74c14
Merge branch 'ui-small-changes' into new-ui-changes
VyshnaviMN Apr 27, 2023
9020a4f
small changes
Ne184 Apr 27, 2023
8619872
small fixes
Ne184 Apr 27, 2023
b807aab
added recordings
VyshnaviMN Apr 27, 2023
f8e4886
update
VyshnaviMN Apr 27, 2023
030e62c
Update README.md
VyshnaviMN Apr 27, 2023
0c6b834
Update README.md
VyshnaviMN Apr 27, 2023
da3a340
Update README.md
VyshnaviMN Apr 27, 2023
5904ea9
Update README.md
VyshnaviMN Apr 27, 2023
3d7ef25
Update README.md
VyshnaviMN Apr 27, 2023
a476e68
Update README.md
VyshnaviMN Apr 27, 2023
f587423
Revert "Update README.md"
VyshnaviMN Apr 27, 2023
43097c2
Update README.md
Ne184 Apr 27, 2023
cf5ac78
readme update
VyshnaviMN Apr 27, 2023
f5441ca
Update README.md
VyshnaviMN Apr 27, 2023
0762bbc
Update README.md
VyshnaviMN Apr 27, 2023
4253a07
Update README.md
VyshnaviMN Apr 27, 2023
1c314dc
Update README.md
VyshnaviMN Apr 27, 2023
b841d3f
small, but important fix
Ne184 Apr 28, 2023
88bc0f4
updated apk
Ne184 Apr 28, 2023
312267f
Update README.md
VyshnaviMN Apr 28, 2023
97f6053
Update README.md
VyshnaviMN Apr 28, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,97 @@ An online indicator and the last message is shown for each contact. Users can ex

### DeToks
**Decentralised TikTok** skeleton app for the CS4160 Blockchain Engineering (2022/23) course.
### Detoks - Offline Token 2
An offline payment application that makes sending and receiving tokens easily.
A user can choose the amount to be received and create a request which can be paid by a preadded contact.
The payment can then be done by scanning the generated QR code and a transaction is then made.
A Eurotoken is minted and verified by a central authority.

Code Link - https://github.com/Ne184/trustchain-superapp/

APK - https://drive.google.com/file/d/1r2p7AvBQ-pumPTApD-cKcR0m7v0g8q1D/view?usp=share_link

### Use case
The application can be used for the following use cases:

**1. Create and store EuroToken**

Creating eurotokens can be performed currently from both the wallet page and admin page by first specifying
the value of the token and then pressing the "Create new coin" button. The new token can then be seen on the screen.

<img src="https://user-images.githubusercontent.com/51911288/234987435-1e243fc7-2fb0-48b9-b92b-15b700237178.gif" width="250">


**2. Send and receive EuroToken between contacts** (by encoding and creating QR for EuroToken)

To send money, you need to press the "Send" button on the screen with the video.
After that, the recipient of the token and positive amount needs to be specified.
If the balance is enough and the specified amount could be created exactly then the QR code is displayed and the receiver can scan it by clicking on the "Scan" button.

**1. Send Money**

<img src="https://user-images.githubusercontent.com/51911288/234988501-b7d9c9e7-196b-44a3-af13-0b1f256bfded.gif" width="250">

**2. Receive Money**

<img src="https://user-images.githubusercontent.com/51911288/234988273-5d7c7dd7-cc49-4ff0-9dc9-05f2d4d6be33.gif" width="250">


**3. Add new contact**

To add a new contact, first press on the "Send" button on the top right of the screen with the displayed video. After that to navigate to the contact page, press on the top right the button "Add Friend". You should now see a screen with two big buttons "Show My Public Key" and "Scan Recipient's Key" the QR code that encodes the public key is shown. Depending on whether you want to add a contact or another user wants to save your contact you should press on one of the buttons.

Pressing on "Show My Public Key" a QR code that encodes your public key is shown.
"Scan Recipient's Key" triggers the scanner and the QR code of the new contact can be scanned.
After that the name should be specified and pressing "Save" will save the new entry.

<img src="https://user-images.githubusercontent.com/51911288/234988799-410dbeba-405b-4a30-97a1-aee00c5b5a39.gif" width="250">


### Double spending
To mitigate double spending, contacts are to be added before users can send or receive EuroTokens.
This makes it easier for admins to track double-spend EuroToken and give users warnings when trying to add malicious users.
Another important concept is used to make sure that the detection of double spending is relatively on time.
After receiving a new token, the token is valid for a limited amount of time (a month).
After that month a token must be verified before being able to re-spend it. The token will be restamped with a new timestamp which makes it a valid euro token.

### Preventing Double Spending

We prevent the same QR Code to be scanned by two different people, thereby preventing Double Spending. This is achieved with the concept of maintaining an addressbook. An addressbook keeps a list of recipients and their corresponding Public Key. In order to send money, the recipient needs to be added to the sender's addressbook.

- More Details
Before sending the token, the public key of the receiver is encoded in the recipients of the token.
Once the token is scanned, prior to adding it to the wallet, the public key of the receiver and the encoded public key of the recipient are compared.
In case they match, the transaction is successful, otherwise, a message for the user is displayed - "This token is not for you!".
Since the public key is unique, this token has a unique receiver.

<img src="https://user-images.githubusercontent.com/51911288/234989059-bcbc8d96-9500-4d31-8120-56175909178f.gif" width="250">


### QR codes explanation
#### Contact QR Code:
In order to be able to send tokens, first the receiver contact needs to be saved as a friend. This could be performed by pressing the button "Add Friend" and then "Show My Public Key" and the QR code that encodes the public key is shown. The sender of the money can then scan it and save it as a contact for later use.
First, the public key is serialized to a JSON object and then it is encoded to bitmap and the QR code is created and shown on the screen of the user.

<img src="https://user-images.githubusercontent.com/51911288/234995696-dfe0f268-b0be-4f5a-be69-f61e5d6ea270.jpg" width="250">


#### Token QR Code:
This QR code is shown once a positive amount less or equal to the balance of the user is specified and the receiver is also chosen from the dropdown menu.
The QR code contains all tokens whose value sums exactly to the specified amount by the user. In case the specified amount can not be formed by the existent tokens then the following message is shown to the user - "Not Successful (not enough money or could get amount)". In case however, the amount can be made by the existing tokens, then those tokens are first serialized to JSON objects, then compressed and the compression is encoded as a bitmap and displayed to the user.
After this, a message -"Successful " with the new balance is shown.

<img src="https://user-images.githubusercontent.com/51911288/234995712-3321eaf0-a533-4309-863b-aedf662573f6.jpg" width="250">


### Limitations
1. Even though we compress and uncompress the QR code, the QR code gets very cluttered while encoding large number of tokens and makes it difficult for the recipient receiving money to scan the QR Code.
2. Cannot do more transactions due to the limited size of QR Code.

### Future work
To detect the double spending, two ideas were discussed which can be implemented in the future:
1. Using the verifivation mechanism, double spending can be easily detected when two users try to verify the same token. The authority will be able to direcly detect the double spender.
2. To prevent double spending in offline transactions, a given precentage of the user tokens is preserved and cannot be used to make payments until the user comes online.

### Digital Euro

Expand Down
2 changes: 1 addition & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@
<activity
android:name="nl.tudelft.trustchain.detoks.DeToksActivity"
android:parentActivityName=".ui.dashboard.DashboardActivity"
android:theme="@style/Fullscreen" />
android:theme="@style/Theme.PeerChat" />

<activity
android:name="nl.tudelft.trustchain.valuetransfer.ValueTransferMainActivity"
Expand Down
3 changes: 3 additions & 0 deletions detoks/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ dependencies {
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation 'androidx.cardview:cardview:1.0.0'

// Material
implementation 'com.google.android.material:material:1.8.0'
Expand All @@ -61,6 +62,8 @@ dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
// implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.4.0")
implementation 'com.google.code.gson:gson:2.10.1'
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"

// Logging
Expand Down
Binary file added detoks/images/DoubleSpendPrevention.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added detoks/images/addFriend.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added detoks/images/createToken.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added detoks/images/friendQR.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added detoks/images/getMoney.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added detoks/images/sendMoney.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added detoks/images/sendingQR.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 0 additions & 1 deletion detoks/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
android:name="nl.tudelft.trustchain.detoks.DeToksActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="@string/title_activity_main_detoks"
android:theme="@style/Fullscreen"
android:windowSoftInputMode="stateHidden" />
</application>

Expand Down
32 changes: 32 additions & 0 deletions detoks/src/main/MainCoin.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import newcoin.*

/**
* Code source is https://medium.com/@vasilyf/lets-implement-a-cryptocurrency-in-kotlin-part-1-blockchain-8704069f8580
*/
fun main(args: Array<String>) {


val blockChain = BlockChain()
val walletA = Wallet.create(blockChain)
val walletB = Wallet.create(blockChain)

println("Wallet A balance: ${walletA.balance}")
println("Wallet B balance: ${walletB.balance}")

val tx1 = Transaction.create(sender = walletA.publicKey, recipient = walletA.publicKey, amount = 100)
tx1.outputs.add(TransactionOutput(recipient = walletA.publicKey, amount = 100, transactionHash = tx1.hash))
tx1.sign(walletA.privateKey)

var genesisBlock = Block(previousHash = "0")
genesisBlock.addTransaction(tx1)
genesisBlock = blockChain.add(genesisBlock)

println("Wallet A balance: ${walletA.balance}")
println("Wallet B balance: ${walletB.balance}")

val tx2 = walletA.sendFundsTo(recipient = walletB.publicKey, amountToSend = 33)
val secondBlock = blockChain.add(Block(genesisBlock.hash).addTransaction(tx2))

println("Wallet A balance: ${walletA.balance}")
println("Wallet B balance: ${walletB.balance}")
}
169 changes: 169 additions & 0 deletions detoks/src/main/java/nl/tudelft/trustchain/detoks/AddFriendFragment.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package nl.tudelft.trustchain.detoks

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import nl.tudelft.trustchain.common.ui.BaseFragment
import nl.tudelft.trustchain.common.util.QRCodeUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import androidx.lifecycle.lifecycleScope
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import nl.tudelft.ipv8.keyvault.PrivateKey
import nl.tudelft.ipv8.keyvault.PublicKey
import nl.tudelft.trustchain.detoks.db.DbHelper
import nl.tudelft.trustchain.detoks.newcoin.OfflineFriend

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
* A simple [Fragment] subclass.
* Use the [AddFriendFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class AddFriendFragment : BaseFragment(R.layout.fragment_add_friend) {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null

private val qrCodeUtils by lazy {
QRCodeUtils(requireContext())
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_friend, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pubKey = view.findViewById<TextView>(R.id.myKey)
var detail = "Scan Public Key of the Recipient to add in your Addressbook"

pubKey.text = detail
val buttonScan = view.findViewById<Button>(R.id.button_scan_public_key)
buttonScan.setOnClickListener {
qrCodeUtils.startQRScanner(this, null, true)
}

val My_QR = view.findViewById<ImageView>(R.id.My_QR)


val buttonShow = view.findViewById<Button>(R.id.button_show)
buttonShow.setOnClickListener {
buttonScan.visibility = View.INVISIBLE
pubKey.text = "Scan the QR Code to add me as a friend!"
val myPublicKey = getIpv8().myPeer.publicKey.keyToBin()
val gsonObject = GsonBuilder().create()
val result = gsonObject.toJson(myPublicKey)

lifecycleScope.launch {
var bitmap = withContext(Dispatchers.Default) {
// qrCodeUtils.createQR(payload.serialize().toHex())
qrCodeUtils.createQR(result)
}
My_QR.visibility = View.VISIBLE
My_QR.setImageBitmap(bitmap)
buttonShow.visibility = View.INVISIBLE
}
}
}

@RequiresApi(Build.VERSION_CODES.O)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val content = qrCodeUtils.parseActivityResult(requestCode,resultCode,data)
Log.v("PublicKey content", content.toString())

val nameFriend = view?.findViewById<EditText>(R.id.name)
nameFriend?.visibility = View.VISIBLE

val buttonSave = view?.findViewById<Button>(R.id.save_friend)
buttonSave?.visibility = View.VISIBLE

buttonSave?.setOnClickListener{
val username = nameFriend?.text
if(nameFriend?.text == null){
Toast.makeText(this.context,"Enter friend's name!", Toast.LENGTH_LONG).show()
} else {
if(content != null) {
val myPublicKey = getIpv8().myPeer.publicKey
val wallet = Wallet.getInstance(
this.requireContext(),
myPublicKey,
getIpv8().myPeer.key as PrivateKey
)
var map = object : TypeToken<ByteArray>() {}.type
val result: ByteArray = Gson().fromJson(content, map)
val newRowId = wallet.addFriend(
OfflineFriend(username.toString(), result)
)
if (newRowId != -1L) {
Toast.makeText(this.context, "Added Friend!", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(this.context, "Duplicate Entry!", Toast.LENGTH_LONG).show()
}
//save call to db

Log.v("Save pub key", content.toString())
Log.v("Name ", username.toString())
val navController = this.findNavController()
navController.navigate(R.id.offlineTransferFragment)
} else {
Toast.makeText(this.context, "Scanning failed!", Toast.LENGTH_LONG).show()
}
}
}

}

companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment AddFriendFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(param1: String, param2: String) =
AddFriendFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package nl.tudelft.trustchain.detoks

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.viewpager2.widget.ViewPager2
import kotlinx.android.synthetic.main.fragment_detoks.*
import mu.KotlinLogging
Expand All @@ -12,7 +17,7 @@ import java.io.FileOutputStream

class DeToksFragment : BaseFragment(R.layout.fragment_detoks) {
private lateinit var torrentManager: TorrentManager
private val logger = KotlinLogging.logger {}
private val logger = KotlinLogging.logger {} // == ({})
private var previousVideoAdapterIndex = 0

private val torrentDir: String
Expand Down Expand Up @@ -49,7 +54,7 @@ class DeToksFragment : BaseFragment(R.layout.fragment_detoks) {
torrentManager = TorrentManager(
File("${requireActivity().cacheDir.absolutePath}/media"),
File("${requireActivity().cacheDir.absolutePath}/torrent"),
DEFAULT_CACHING_AMOUNT
DEFAULT_CACHING_AMOUNT,
)
}

Expand All @@ -59,6 +64,22 @@ class DeToksFragment : BaseFragment(R.layout.fragment_detoks) {
viewPagerVideos.adapter = VideosAdapter(torrentManager)
viewPagerVideos.currentItem = 0
onPageChangeCallback()
val buttonOffline = view.findViewById<Button>(R.id.button_offline)
buttonOffline.setOnClickListener {
// OfflineTransferFragment.newInstance("param1", "param2")
// val activity = view.context as (AppCompatActivity)
val navController = view.findNavController()
navController.navigate(R.id.offlineTransferFragment)
Log.v("Offline fragment", "hello")
Log.v("Offline fragment", "activated")
}
val walletButton = view.findViewById<Button>(R.id.wallet_button)
walletButton.setOnClickListener {
val navController = view.findNavController()
navController.navigate(R.id.walletFragment)
Log.v("Wallet fragment", "hello")
Log.v("Wallet fragment", "activated")
}
}

/**
Expand Down
Loading